F#: Practicing Units of Measure

I decided to create my own car kata.
In doing so, I decided to leverage the UOM (Unit of Measure) feature in F#. This essentially constrains how one calculates values that are associated to specific units of measure. Moreover, this is meant to avoid silly mistakes that occur when one confuses units of measurement for a given calculation.

Here’s what I wrote:

(*Types*)
[<Measure>] type mph

type Speed =    MPH of int<mph>
type Pressure = Quarter | Half | Full

type Mode =
    | Park  | Nuetral
    | Drive | Reverse

(*Functions*)
let applyGas pressure mode = mode |> function
    | Park
    | Nuetral -> MPH 0<mph>

    | Drive
    | Reverse -> match pressure with
                 | Quarter -> MPH  25<mph>
                 | Half    -> MPH  50<mph>
                 | Full    -> MPH 100<mph>

(*Client*)
let result = Drive |> applyGas Half

Here’s the output:

val result : Speed = MPH 50

I then restructured the code to the following:

module TempImpl

(*Types*)
[<Measure>] type mph

type Speed =    MPH of int<mph>
type Pressure = Quarter | Half | Full

type Mode =
    | Park  | Nuetral
    | Drive | Reverse

(*Functions*)
let applyGas pressure mode = mode |> function

    | Park  | Nuetral -> MPH 0<mph>
    | Drive | Reverse -> 
      match pressure with
      | Quarter -> MPH  25<mph>
      | Half    -> MPH  50<mph>
      | Full    -> MPH 100<mph>

(*Client*)
let result = Drive |> applyGas Half
Advertisements

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

%d bloggers like this: