C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We specify width and height variables. These are 10 and 5 feet in size. We use the feet measurement.
Finally: We create an areaOfBox variable. This has type of int with measurement area. It is equal to a feet unit times another.
So: AreaOfBox here can only be created by multiplying two "feet" measurements together. They cannot be added or computed in another way.
F# program that uses measure
// Use feet as a unit of measure.
[<Measure>] type feet
// Area is feet squared.
[<Measure>] type area = feet ^ 2
// Create a width and a height in feet.
let width = 10<feet>
let height = 5<feet>
// Get the area by multiplying the width and the height.
// ... This is an area measure.
let (areaOfBox : int<area>) = width * height
// Write value of areaOfBox.
printfn "%A" areaOfBox
Output
50
However: Area is not the result of a division. It is the result of a multiplication (a squaring of feet).
So: The program does not compile. Another unit, other than area, would need to exist and be used for the division.
F# program that causes compile-time measure error
[<Measure>] type feet
[<Measure>] type area = feet ^ 2
let width = 10<feet>
let height = 5<feet>
// This does not compile because an area is not based on a division.
// ... It must be a multiplication of feet, not a division of feet.
let (areaOfBox : int<area>) = width / height
Output
error FS0001: The type 'int<area>' does not match the type 'int'
Tip: Measures are a way to introduce more compile-time validation into a program. They can help us "prove" a program is correct.
Constraints: Measures are a form of constraint-checking. For critical programs where an error is catastrophic, they are more valuable.
Quote: F# supports static checking of units of measure. Units of measure, or measures for short, are like types in that they can appear as parameters to other types and values... and are checked for consistency by the type-checker (F# Language Specification).