Map and Set in F#
Immutable keyed and unique collections; adds return new ones.
// Map and Set are immutable: every add returns a new collection.
let stores = Map [ "Willow", 14; "Bramble", 9 ]
let updated = stores |> Map.add "Clover" 18
printfn "Clover stored: %d" updated.["Clover"]
printfn "Missing hive: %A" (updated |> Map.tryFind "Thistle")
updated
|> Map.iter (fun hive jars -> printfn "%s: %d jars" hive jars)
let spring = Set ["Willow"; "Bramble"]
let autumn = Set ["Bramble"; "Clover"]
printfn "Surveyed twice: %A" (Set.intersect spring autumn)
printfn "Whole yard: %d hives" (Set.union spring autumn |> Set.count)
How it works
Map.addgives back a bigger map; the original stands.Map.tryFindreturns an Option instead of throwing.Set.intersectandunionspeak survey algebra.
Keywords and builtins used here
funlet
The run, in numbers
- Lines
- 14
- Characters to type
- 547
- Tokens
- 128
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 118 seconds.
Step 1 of 3 in Collections, step 16 of 27 in Language basics.