typestar

Units of measure in F#

kg and jar ride the type system; wrong units will not compile.

// Units of measure ride the type system: kg + km will not compile.
[<Measure>] type kg
[<Measure>] type jar

let harvest = 12.4<kg>
let perJar = 0.34<kg/jar>

// The division cancels units: kg over kg/jar leaves jars.
let jars = harvest / perJar
printfn "Jars this pull: %.0f" (float jars)

let combined = harvest + 3.1<kg>
printfn "With the late frames: %.1f kg" (float combined)
// let broken = harvest + 2.0<jar>  // the compiler stops this line

How it works

  1. [<Measure>] type kg declares a unit with no runtime cost.
  2. 0.34<kg/jar> types a rate; division cancels the units.
  3. The commented line shows what the compiler refuses.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
449
Tokens
83
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 2 of 3 in Signatures & laziness, step 23 of 27 in Language basics.

← Previous Next →