typestar

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

  1. Map.add gives back a bigger map; the original stands.
  2. Map.tryFind returns an Option instead of throwing.
  3. Set.intersect and union speak survey algebra.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Collections, step 16 of 27 in Language basics.

← Previous Next →

Map and Set in other languages