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
Map.tryFindstarts the chain with an Option.Option.filterturns a weak answer back into None.defaultValuelands the chain on solid ground.
Keywords and builtins used here
funlet
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.
Step 3 of 3 in Idioms, step 21 of 27 in Language basics.