75 people like it.

Units of Measure

Show's how to define units of measure to add stronger typing to your numerical functions.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
// define some units of measure
[<Measure>]type litre
[<Measure>]type pint

// define some volumens
let vol1 = 2.5<litre>
let vol2 = 2.5<pint>

// define the ratio of pints to litres
let ratio =  1.0<litre> / 1.76056338<pint>

// a function to convert prints to litres
let convertPintToLitre pints =
    pints * ratio

// preforme the conversion and add the values
let newVol = vol1 + (convertPintToLitre vol2)
Multiple items
type MeasureAttribute =
  inherit Attribute
  new : unit -> MeasureAttribute

Full name: Microsoft.FSharp.Core.MeasureAttribute

--------------------
new : unit -> MeasureAttribute
[<Measure>]
type litre

Full name: Script.litre
[<Measure>]
type pint

Full name: Script.pint
val vol1 : float<litre>

Full name: Script.vol1
val vol2 : float<pint>

Full name: Script.vol2
val ratio : float<litre/pint>

Full name: Script.ratio
val convertPintToLitre : pints:float<'u> -> float<'u litre/pint>

Full name: Script.convertPintToLitre
val pints : float<'u>
val newVol : float<litre>

Full name: Script.newVol
Next Version Raw view Test code New version

More information

Link:http://fssnip.net/D
Posted:14 years ago
Author:Robert Pickering
Tags: units of measure