Maps, Sets and Other Collections
Recursive processing, small sequences Performance, interop Lazy pipelines, streaming Dictionary / HashSet Hot paths, caches
// Map: immutable, ordered (balanced tree) dictionary
let ages = Map [ "Ana", 30; "Bo", 25 ]
ages["Ana"] // 30 (throws if missing)
ages.TryFind "Cy" // None
Map.tryFind "Bo" ages // Some 25
let ages2 = ages |> Map.add "Cy" 41 |> Map.remove "Bo"
Map.containsKey "Ana" ages
ages |> Map.map (fun _ age -> age + 1)
ages |> Map.filter (fun _ age -> age > 26)
ages |> Map.toList // [("Ana", 30); ("Bo", 25)] (sorted by key)
ages |> Map.fold (fun acc _ v -> acc + v) 0 // 55
ages |> Map.change "Ana" (Option.map ((+) 1)) // update if present
Map.keys ages, Map.values ages // (F# 6+)
// Word count
let wordCounts (text: string) =
text.Split(' ', System.StringSplitOptions.RemoveEmptyEntries)
|> Array.countBy id
|> Map.ofArray
// Set: immutable, ordered
let s1 = Set [1; 2; 3]
let s2 = set [3; 4]
Set.union s1 s2, Set.intersect s1 s2, Set.difference s1 s2 // set [1..4], set [3], set [1; 2]
s1.Contains 2, Set.add 9 s1, Set.isSubset (set [1]) s1
// .NET mutable collections (for performance or interop)
open System.Collections.Generic
let dict = Dictionary<string,
…