[racket] Numbers with dimensions

From: Konrad Hinsen (konrad.hinsen at fastmail.net)
Date: Fri Oct 25 06:14:24 EDT 2013

Alvin Schatte writes:

 > Is there a library or package that combines numbers and their
 > operations with dimensions that may be associated with them?

Apparently not, from what I learn from previous discussions on this list.

Doing this well is actually far from trivial, in any language, but it
would make for a nice research project that could lead to something
practically very useful.

There are two aspects to dealing with physical quantities, which I think
are best considered separately: dimensions and units.

Dimensions are length, time, volume, velocity, etc. Addition,
subtraction, and comparison of quantities is allowed only when their
dimensions are equal. Multiplication and division are allowed for any
combination of dimension, but produce a result of a different dimension.

Since dimensions impose constraints on allowed mathematical
expressions, it is tempting to implement them as types and have a
static type checker verify dimensional consistency at compile
time. However, many (most?) type systems are not quite up to the
task. I haven't looked at Typed Racket enough to be able to say if it
could handle the task. Most dimension-checking approaches I have seen
use dynamic typing with run-time checks. In fact, the only approaches
I know of that use static type checking are Boost.Units for C++
(http://www.boost.org/doc/libs/1_54_0/doc/html/boost_units.html),
and the units package for Haskell (http://hackage.haskell.org/package/units).

The tricky aspect of dimensions when seen as types is there is an
infinite number of dimensions, so it's not possible to provide an
exhaustive list.  Multiplying two lengths results in an area, which is
the square of a length. Multiplying N lengths yields a quantity of
dimension length^N, for any N. Every unit system has a finite number
of base dimensions, in which every possible dimension can be expressed
as a product of integer powers of the base dimensions. Some
pathological unit systems even require fractional powers, but they are
luckily disappearing quickly.

Once you have dimensions, units are trivial to implement: every unit
is simply a constant of the dimensional-quantity type. In fact, when
you say "2 meters", you really mean "a length twice as long as the
length we decided to call a meter". A meter is thus just a specific
length value.

Konrad.

Posted on the users mailing list.