typestar

Option pipelines in F#

map, filter and defaultValue chain maybes with no null checks.

// Option.map and bind chain maybes without a single null check.
let inventory = Map [ "Willow", 14; "Bramble", 3 ]

let jarsFor hive = inventory |> Map.tryFind hive

let shipping hive =
    hive
    |> jarsFor
    |> Option.filter (fun jars -> jars >= 6)
    |> Option.map (fun jars -> sprintf "%s ships %d jars" hive jars)
    |> Option.defaultValue (sprintf "%s holds its stock" hive)

["Willow"; "Bramble"; "Thistle"]
|> List.iter (shipping >> printfn "%s")

How it works

  1. Map.tryFind starts the chain with an Option.
  2. Option.filter turns a weak answer back into None.
  3. defaultValue lands the chain on solid ground.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
441
Tokens
106
Three-star pace
65 tpm

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

Type this snippet

Step 3 of 3 in Idioms, step 21 of 27 in Language basics.

← Previous Next →