Interactive Session #11: Units of Measure

F# includes a language feature to annotate your code with units of measure like meter, second or kilogram, preferably from the SI system. These units are statically checked during compile time and will not be part of the compiled code.

> [<Measure>] type m;;

[<Measure>]
type m

> [<Measure>] type s;;

[<Measure>]
type s

> let v (s:float<m>) (t:float<s>) = s/t;;

val v : float<m> -> float<s> -> float<m/s>

> v 100.0<m> 4.5<s>;;
val it : float<m/s> = 22.22222222

You may recognize that the type of the speed function ‘v’ includes a type float<m/s> automatically derived from the basic types and units of measure float<m> and float<s>.

The F# PowerPack includes the SI units of measure (to install F# PowerPack on Linux / Mono look here).

> #r "FSharp.PowerPack.dll";;

--> Referenced '/usr/local/lib/FSharp-2.0.0.0/bin/FSharp.PowerPack.dll'

> open SI;;
> 1.0<kg>;;
val it : float<kg> = 1.0

The complete list of SI units available in module SI can be found here.

> let w = 1.0<kg>;;

val w : float<kg> = 1.0

> let g = 9.81<m/s^2>;;

val g : float<m/s ^ 2> = 9.81

> let f = w * g;;

val f : float<kg m/s ^ 2> = 9.81

Further reading:

Advertisements
This entry was posted in Algorithms, Getting Started, Language. Bookmark the permalink.

One Response to Interactive Session #11: Units of Measure

  1. Pingback: Rick Minerich's Development Wonderland : F# Discoveries This Week 10/03/2010

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s