Sunday, August 20, 2017

Units of Measure in F#

An interesting (and seemingly very useful feature) of F#: units-of-measure types, which help the compiler reason about correctness. 

https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/units-of-measure

> [<Measure>] type cm;;
 [<Measure>]
 type cm

> [<Measure>] type mile;;
 [<Measure>]
 type mile

> [<Measure>] type hour;;
 [<Measure>]
 type hour

> let distance = 20.0<mile>;;
 val distance : float<mile> = 20.0

> let duration = 12.0<hour>;;
 val duration : float<hour> = 12.0

> let speed = distance / duration;;
 val speed : float<mile/hour> = 1.666666667

> speed + 2<cm>;;
 Stopped due to error
 System.Exception: Operation could not be completed due to earlier error
 The type 'int<cm>' does not match the type 'float<mile/hour>' at 3,8
 The type 'int<cm>' does not match the type 'float<mile/hour>' at 3,6


> speed + 1.0<mile/hour>;;
 val it : float<mile/hour> = 2.666666667

No comments:

Post a Comment