Skip to content
Immutable Collections
step 1/5

Reading — step 1 of 5

Learn

~1 min readRecords and Collections

F# wraps .NET's collections with immutable, FP-friendly modules:

List — singly-linked, the default for short sequences:

let xs = [1; 2; 3; 4; 5]
let head = List.head xs                      // 1
let tail = List.tail xs                       // [2; 3; 4; 5]
let doubled = xs |> List.map (fun n -> n * 2)
let evens = xs |> List.filter (fun n -> n % 2 = 0)
let sum = xs |> List.sum

Array — mutable, contiguous; use Array.map etc. for stream ops:

let arr = [|1; 2; 3|]
let doubled = arr |> Array.map ((*) 2)

Map — immutable map (keyed):

let ages = Map.ofList [("alice", 30); ("bob", 25)]
let aliceAge = Map.find "alice" ages
let updated = Map.add "carol" 40 ages         // returns new map
let removed = Map.remove "bob" ages

Set — immutable unique elements:

let primes = Set.ofList [2; 3; 5; 7; 11]
let has = Set.contains 7 primes               // true
let bigger = Set.add 13 primes

Seq — lazy enumerable, like .NET IEnumerable:

seq { for i in 1..10 -> i * i }
|> Seq.filter (fun n -> n > 20)
|> Seq.take 3
|> Seq.toList

Most-used pipeline operators:

  • List.map, List.filter, List.fold, List.iter
  • List.length, List.sum, List.average
  • List.sort, List.sortBy, List.sortByDescending
  • List.groupBy, List.distinct
  • List.zip, List.unzip

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…