HORIZON HASKELLDocslts/ghc-9.10.x248f8f02026-10-05Search names, modules, packages, or :: a typeCtrl K

GHC 9.10.3 · lts/ghc-9.10.x · 248f8f0 · 2026-10-05

Moduledimensional-1.5Haskell2010

Numeric.Units.Dimensional

Summary

In this module we provide data types for performing arithmetic with physical quantities and units. Information about the physical dimensions of the quantities/units is embedded in their types and the validity of operations is verified by the type checker at compile time. The wrapping and unwrapping of numerical values as quantities is done by multiplication and division of units, of which an incomplete set is provided.

We limit ourselves to "Newtonian" physics. We do not attempt to accommodate relativistic physics in which e.g. addition of length and time would be valid.

As far as possible and/or practical the conventions and guidelines of NIST's "Guide for the Use of the International System of Units (SI)" [1] are followed. Occasionally we will reference specific sections from the guide and deviations will be explained.

Disclaimer

Merely an engineer, the author doubtlessly uses a language and notation that makes mathematicians and physicists cringe. He does not mind constructive criticism (or pull requests).

The sets of functions and units defined herein are incomplete and reflect only the author's needs to date. Again, patches are welcome.

Usage

Preliminaries

This module requires GHC 8 or later. We utilize Data Kinds, TypeNats, Closed Type Families, etc. Clients of the module are generally not required to use these extensions.

Clients probably will want to use the NegativeLiterals extension though.

Examples

We have defined operators and units that allow us to define and work with physical quantities. A physical quantity is defined by multiplying a number with a unit (the type signature is optional).

v :: Velocity Double
v = 90 *~ (kilo meter / hour)

It follows naturally that the numerical value of a quantity is obtained by division by a unit.

numval :: Double
numval = v /~ (meter / second)

The notion of a quantity as the product of a numerical value and a unit is supported by 7.1 "Value and numerical value of a quantity" of [1]. While the above syntax is fairly natural, it is unfortunate that it must violate a number of the guidelines in [1], in particular 9.3 "Spelling unit names with prefixes", 9.4 "Spelling unit names obtained by multiplication", 9.5 "Spelling unit names obtained by division".

As a more elaborate example of how to use the module, we define a function for calculating the escape velocity of a celestial body [2].

escapeVelocity :: (Floating a) => Mass a -> Length a -> Velocity a
escapeVelocity m r = sqrt (two * g * m / r)
  where
      two = 2 *~ one
      g = 6.6720e-11 *~ (newton * meter ^ pos2 / kilo gram ^ pos2)

For completeness, we should also show an example of the error messages we will get from GHC when performing invalid arithmetic. In the best case, GHC will be able to use the type synonyms we have defined in its error messages.

let x = 1 *~ meter + 1 *~ second

Couldn't match type 'Numeric.NumType.DK.Integers.Zero
               with 'Numeric.NumType.DK.Integers.Pos1
Expected type: Unit 'Metric DLength a
  Actual type: Unit 'Metric DTime a
In the second argument of `(*~)', namely `second'
In the second argument of `(+)', namely `1 *~ second'

In other cases, the error messages aren't very friendly.

let x = 1 *~ meter / (1 *~ second) + 1 *~ kilo gram

Couldn't match type 'Numeric.NumType.DK.Integers.Zero
               with 'Numeric.NumType.DK.Integers.Neg1
Expected type: Quantity DMass a
  Actual type: Dimensional
                 ('DQuantity V.* 'DQuantity) (DLength / DTime) a
In the first argument of `(+)', namely `1 *~ meter / (1 *~ second)'
In the expression: 1 *~ meter / (1 *~ second) + 1 *~ kilo gram
In an equation for `x':
      x = 1 *~ meter / (1 *~ second) + 1 *~ kilo gram

It is the author's experience that the usefulness of the compiler error messages is more often than not limited to pinpointing the location of errors.

Notes

Future work

While there is an insane amount of units in use around the world it is reasonable to provide those in relatively widespread use. Units outside of SI will most likely be added on an as-needed basis.

Additional physics models could be implemented. See [3] for ideas.

Related work

Henning Thielemann's numeric prelude has a physical units library, however, checking of dimensions is dynamic rather than static. Aaron Denney has created a toy example of statically checked physical dimensions covering only length and time. HaskellWiki has pointers [4] to these.

Also see Samuel Hoffstaetter's blog post [5] which uses techniques similar to this library.

Libraries with similar functionality exist for other programming languages and may serve as inspiration. The author has found the Java library JScience [6] and the Fortress programming language [7] particularly noteworthy.

References

  1. https://www.nist.gov/pml/special-publication-811

  2. https://en.wikipedia.org/wiki/Escape_velocity

  3. https://web.archive.org/web/20080905151927/http://jscience.org/api/org/jscience/physics/models/package-summary.html

  4. https://wiki.haskell.org/Physical_units

  5. https://liftm.wordpress.com/2007/06/03/scientificdimension-type-arithmetic-and-physical-units-in-haskell/

  6. http://jscience.org/

  7. https://github.com/stokito/fortress-lang

  • 25 types
  • 2 classes
  • 69 values
  • MonoLocalBinds
  • ScopedTypeVariables
  • TypeFamilies
  • ConstraintKinds
  • DataKinds
  • StandaloneDeriving
  • DeriveDataTypeable
  • DeriveGeneric
  • TypeSynonymInstances
  • FlexibleContexts
  • FlexibleInstances
  • KindSignatures
  • RoleAnnotations
  • GeneralizedNewtypeDeriving
  • RankNTypes
  • TypeOperators
  • ExplicitNamespaces
  • ExplicitForAll
  • Packagedimensional-1.5
  • Exports101
  • LanguageHaskell2010
  • LicenceBSD-3-Clause
  • SourceDimensional.hs

Types

4 declarations

Our primary objective is to define a data type that can be used to represent (while still differentiating between) units and quantities. There are two reasons for consolidating units and quantities in one data type. The first being to allow code reuse as they are largely subject to the same operations. The second being that it allows reuse of operators (and functions) between the two without resorting to occasionally cumbersome type classes.

The relationship between (the value of) a Quantity, its numerical value and its Unit is described in 7.1 "Value and numerical value of a quantity" of [1]. In short a Quantity is the product of a number and a Unit. We define the *~ operator as a convenient way to declare quantities as such a product.

familydata family Dimensional (v :: Variant) :: Dimension -> Type -> Type
#

A dimensional value, either a Quantity or a Unit, parameterized by its Dimension and representation.

Instances34Generic1, Demotable, Functor, Eq1, Ord1, NFData, …
datadata Metricality
#

Encodes whether a unit is a metric unit, that is, whether it can be combined with a metric prefix to form a related unit.

Constructors

  • Metric

    Capable of receiving a metric prefix.

  • NonMetric

    Incapable of receiving a metric prefix.

Instances6Eq, Data, Ord, Generic, NFData, Rep

Physical Dimensions

1 declaration

The phantom type variable d encompasses the physical dimension of a Dimensional. As detailed in [5], there are seven base dimensions, which can be combined in integer powers to a given physical dimension. We represent physical dimensions as the powers of the seven base dimensions that make up the given dimension. The powers are represented using NumTypes. For convenience, we collect all seven base dimensions in a data kind Dimension.

We could have chosen to provide type variables for the seven base dimensions in Dimensional instead of creating a new data kind Dimension. However, that would have made any type signatures involving Dimensional very cumbersome. By encompassing the physical dimension in a single type variable we can "hide" the cumbersome type arithmetic behind convenient type classes as will be seen later.

datadata Dimension
#

Represents a physical dimension in the basis of the 7 SI base dimensions, where the respective dimensions are represented by type variables using the following convention:

  • l: Length

  • m: Mass

  • t: Time

  • i: Electric current

  • th: Thermodynamic temperature

  • n: Amount of substance

  • j: Luminous intensity

For the equivalent term-level representation, see Dimension'

Instances2HasDimension, HasDynamicDimension

Dimension Arithmetic

When performing arithmetic on units and quantities, the arithmetics must be applied to both the numerical values of the Dimensionals but also to their physical dimensions. The type level arithmetic on physical dimensions is governed by closed type families expressed as type operators.

We could provide the Mul and Div classes with full functional dependencies but that would be of limited utility as there is no limited use for "backwards" type inference. Efforts are underway to develop a type-checker plugin that does enable these scenarios, e.g. for linear algebra.

familytype family (*) (a :: Dimension) (b :: Dimension) :: Dimension where
#

Multiplication of dimensions corresponds to addition of the base dimensions' exponents.

Equations

  • (*) DOne d = d
  • (*) d DOne = d
  • (*) ('Dim l m t i th n j) ('Dim l' m' t' i' th' n' j') = 'Dim (l + l') (m + m') (t + t') (i + i') (th + th') (n + n') (j + j')
familytype family (/) (a :: Dimension) (d :: Dimension) :: Dimension where
#

Division of dimensions corresponds to subtraction of the base dimensions' exponents.

Equations

  • (/) d DOne = d
  • (/) d d = DOne
  • (/) ('Dim l m t i th n j) ('Dim l' m' t' i' th' n' j') = 'Dim (l - l') (m - m') (t - t') (i - i') (th - th') (n - n') (j - j')
familytype family (^) (d :: Dimension) (x :: TypeInt) :: Dimension where
#

Powers of dimensions correspond to multiplication of the base dimensions' exponents by the exponent.

We limit ourselves to integer powers of Dimensionals as fractional powers make little physical sense.

Equations

typetype Recip (d :: Dimension) = DOne / d
#

The reciprocal of a dimension is defined as the result of dividing DOne by it, or of negating each of the base dimensions' exponents.

Term Level Representation of Dimensions

To facilitate parsing and pretty-printing functions that may wish to operate on term-level representations of dimension, we provide a means for converting from type-level dimensions to term-level dimensions.

datadata Dimension'
#

A physical dimension, encoded as 7 integers, representing a factorization of the dimension into the 7 SI base dimensions. By convention they are stored in the same order as in the Dimension data kind.

Constructors

Instances11Eq, Data, Ord, Show, Generic, Semigroup, …
classclass HasDynamicDimension a => HasDimension a where
#

Dimensional values inhabit this class, which allows access to a term-level representation of their dimension.

Methods

Instances5HasDimension

Dimensional Arithmetic

16 declarations
value(/~) :: Fractional a => Quantity d a -> Unit m d a -> a
#

Divides a Quantity by a Unit of the same physical dimension, obtaining the numerical value of the quantity expressed in that unit.

value(^)
  1. :: (Fractional a, KnownTypeInt i, KnownVariant v, KnownVariant (Weaken v))
  2. => Dimensional v d1 a
  3. -> Proxy i
  4. -> Dimensional (Weaken v) (d1 ^ i) a
#

Raises a Quantity or Unit to an integer power.

Because the power chosen impacts the Dimension of the result, it is necessary to supply a type-level representation of the exponent in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ... are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are also reexported by Numeric.Units.Dimensional.Prelude.

The intimidating type signature captures the similarity between these operations and ensures that composite Units are NonMetric.

value(^/)
  1. :: (KnownTypeInt n, Floating a)
  2. => Quantity d a
  3. -> Proxy n
  4. -> Quantity (NRoot d n) a
#

Computes the nth root of a Quantity using **.

The NRoot type family will prevent application of this operator where the result would have a fractional dimension or where n is zero.

Because the root chosen impacts the Dimension of the result, it is necessary to supply a type-level representation of the root in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ... are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are also reexported by Numeric.Units.Dimensional.Prelude.

Also available in prefix form, see nroot.

valuenroot
  1. :: (KnownTypeInt n, Floating a)
  2. => Proxy n
  3. -> Quantity d a
  4. -> Quantity (NRoot d n) a
#

Computes the nth root of a Quantity using **.

The NRoot type family will prevent application of this operator where the result would have a fractional dimension or where n is zero.

Because the root chosen impacts the Dimension of the result, it is necessary to supply a type-level representation of the root in the form of a Proxy to some TypeInt. Convenience values pos1, pos2, neg1, ... are supplied by the Numeric.NumType.DK.Integers module. The most commonly used ones are also reexported by Numeric.Units.Dimensional.Prelude.

n must not be zero. Negative roots are defined such that nroot (Proxy :: Proxy (Negate n)) x == nroot (Proxy :: Proxy n) (recip x).

Also available in operator form, see ^/.

valuesqrt :: Floating a => Quantity d a -> Quantity (Sqrt d) a
#

Computes the square root of a Quantity using **.

The NRoot type family will prevent application where the supplied quantity does not have a square dimension.

Property
(x :: Area Double) >= _0 ==> sqrt x == nroot pos2 x
valuecbrt :: Floating a => Quantity d a -> Quantity (Cbrt d) a
#

Computes the cube root of a Quantity using **.

The NRoot type family will prevent application where the supplied quantity does not have a cubic dimension.

Property
(x :: Volume Double) >= _0 ==> cbrt x == nroot pos3 x

Transcendental Functions

valueatan2 :: RealFloat a => Quantity d a -> Quantity d a -> Dimensionless a
#

The standard two argument arctangent function. Since it interprets its two arguments in comparison with one another, the input may have any dimension.

Example1 expression
atan2 _0 _10.0
Example1 expression
atan2 _1 _01.5707963267948966
Example1 expression
atan2 _0 (negate _1)3.141592653589793
Example1 expression
atan2 (negate _1) _0-1.5707963267948966

Operations on Collections

Here we define operators and functions to make working with homogeneous lists of dimensionals more convenient.

We define two convenience operators for applying units to all elements of a functor (e.g. a list).

valuesum :: (Num a, Foldable f) => f (Quantity d a) -> Quantity d a
#

The sum of all elements in a foldable structure.

Example1 expression
sum ([] :: [Mass Double])0.0 kg
Example1 expression
sum [12.4 *~ meter, 1 *~ foot]12.7048 m
valueproduct :: (Num a, Foldable f) => f (Dimensionless a) -> Dimensionless a
#

The product of all elements in a foldable structure.

Example1 expression
product ([] :: [Dimensionless Double])1.0
Example1 expression
product [pi, _4, 0.36 *~ one]4.523893421169302
valuenFromTo
  1. :: (Fractional a, Integral b)
  2. => Quantity d a

    The initial value.

  3. -> Quantity d a

    The final value.

  4. -> b

    The number of intermediate values. If less than one, no intermediate values will result.

  5. -> [Quantity d a]
#

Returns a list of quantities between given bounds.

Property
n <= 0 ==> nFromTo (x :: Mass Double) (y :: Mass Double) n == [x, y]
Property
(x :: Length Double) <= (y :: Length Double) ==> all (\z -> x <= z && z <= y) (nFromTo x y n)
Example1 expression
nFromTo _0 _3 2[0.0,1.0,2.0,3.0]
Example1 expression
nFromTo _1 _0 7[1.0,0.875,0.75,0.625,0.5,0.375,0.25,0.125,0.0]
Example1 expression
nFromTo _0 _1 (-5)[0.0,1.0]

Dimension Synonyms

8 declarations

Using our Dimension data kind we define some type synonyms for convenience. We start with the base dimensions, others can be found in Numeric.Units.Dimensional.Quantities.

Quantity Synonyms

8 declarations

Using the above type synonyms we can define type synonyms for quantities of particular physical dimensions.

Again we limit ourselves to the base dimensions, others can be found in Numeric.Units.Dimensional.Quantities.

Constants

12 declarations

For convenience we define some constants for small integer values that often show up in formulae. We also throw in pi and tau for good measure.

Constructing Units

5 declarations
valuesiUnit :: (KnownDimension d, Num a) => Unit 'NonMetric d a
#

A polymorphic Unit which can be used in place of the coherent SI base unit of any dimension. This allows polymorphic quantity creation and destruction without exposing the Dimensional constructor.

valueone :: Num a => Unit 'NonMetric DOne a
#

The unit one has dimension DOne and is the base unit of dimensionless values.

As detailed in 7.10 "Values of quantities expressed simply as numbers: the unit one, symbol 1" of [1], the unit one generally does not appear in expressions. However, for us it is necessary to use one as we would any other unit to perform the "wrapping" of dimensionless values.

valuemkUnitR :: Floating a => UnitName m -> ExactPi -> Unit m1 d a -> Unit m d a
#

Forms a new atomic Unit by specifying its UnitName and its definition as a multiple of another Unit.

Use this variant when the scale factor of the resulting unit is irrational or Approximate. See mkUnitQ for when it is rational and mkUnitZ for when it is an integer.

Note that supplying zero as a definining quantity is invalid, as the library relies upon units forming a group under multiplication.

Supplying negative defining quantities is allowed and handled gracefully, but is discouraged on the grounds that it may be unexpected by other readers.

valuemkUnitZ :: Num a => UnitName m -> Integer -> Unit m1 d a -> Unit m d a
#

Forms a new atomic Unit by specifying its UnitName and its definition as a multiple of another Unit.

Use this variant when the scale factor of the resulting unit is an integer. See mkUnitQ for when it is rational and mkUnitR for the general case.

For more information see mkUnitR.

Unit Metadata

5 declarations
valueexactValue :: Unit m d a -> ExactPi
#

Extracts the exact value of a Unit, expressed in terms of the SI coherent derived unit (see siUnit) of the same Dimension.

Note that the actual value may in some cases be approximate, for example if the unit is defined by experiment.

Pretty Printing

1 declaration
valueshowIn :: (Show a, Fractional a) => Unit m d a -> Quantity d a -> String
#

Shows the value of a Quantity expressed in a specified Unit of the same Dimension.

Uses non-breaking spaces between the value and the unit, and within the unit name.

Example1 expression
putStrLn $ showIn watt $ (37 *~ volt) * (4 *~ ampere)148.0 W

On Functor, and Conversion Between Number Representations

3 declarations

We intentionally decline to provide a Functor instance for Dimensional because its use breaks the abstraction of physical dimensions.

If you feel your work requires this instance, it is provided as an orphan in Numeric.Units.Dimensional.Functor.

classclass KnownVariant (v :: Variant) where
#

A KnownVariant is one whose term-level Dimensional values we can represent with an associated data family instance and manipulate with certain functions, not all of which are exported from the package.

Each validly constructed type of kind Variant has a KnownVariant instance.

Methods

  • dmap :: (a1 -> a2) -> Dimensional v d a1 -> Dimensional v d a2

    Maps over the underlying representation of a dimensional value. The caller is responsible for ensuring that the supplied function respects the dimensional abstraction. This means that the function must preserve numerical values, or linearly scale them while preserving the origin.

Instances2KnownVariant
valuechangeRep
  1. :: (KnownVariant v, Real a, Fractional b)
  2. => Dimensional v d a
  3. -> Dimensional v d b
#

Convenient conversion between numerical types while retaining dimensional information.

Example2 expressions
let x = (37 :: Rational) *~ poundMasschangeRep x :: Mass Double16.78291769 kg

Lenses

1 declaration

These functions are compatible with the lens library.