1. Thijs Alkemade
  2. haskell-unittyped


Clone wiki

haskell-unittyped / Examples

Some examples

Multiplication and division

The rules involving multiplication and division of units are enforced to on the type level:

*Main> (1 meter / second) * 5 second
5.0 m/ss
*Main> 2 meter + (1 meter / second) * 5 second
7.0 m

Units that do not match will give a type error like:

*Main> meter + second

    Couldn't match type 'False with 'True
    When using functional dependencies to combine
      And 'False 'False 'False,
        arising from the dependency `a b -> c'
        in the instance declaration in `UnitTyped.Units'
      And 'False 'False 'True,
        arising from a use of `+' at <interactive>:14:7
    In the expression: meter + second
    In an equation for `it': it = meter + second

It's horribly ugly, but that's the price for letting the type checker figure out if they are equal...


*Main> (42 kilo meter) `as` mile
26.097590073968025 mile
*Main> gallon `as` (cubic (deci meter))
4.546089999999999 dmdmdm#

Earth's gravity

*Main> let mass = 5.9736e24 kilo gram
*Main> let radius = 6.371e6 meter
*Main> let gravity = g * mass / (square radius)
*Main> gravity
9.821939152602999 mmm/kg/(ss)kg/(mm#)
*Main> gravity `as` meter / square second
9.821939152602999 m/(ss#)


Most values are defined as (Fractional f) => f. So it is also possible to use Rationals, and never lose precision:

*Main> coerce ((1 % 2) . meter) foot
625 % 381 ft


> (1 % 2) . meter `as` foot
625 % 381 ft
*Main> 61 second < 1 minute