Map

Immutable maps. Keys are ordered by F# generic comparison.

Maps based on generic comparison are efficient for small keys. They are not a suitable choice if keys are recursive data structures or if keys require bespoke comparison semantics. All members of this class are thread-safe. It's recommended to use the module functions as F# can then determine types implicitly.

Creating

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
let employees =
  Map.empty
  |> Map.add "Joe" 1001
  |> Map.add "Jeff" 1002
  |> Map.add "George" 1003

// Map module usage, preferred
let capitals =
  [ "Argentina", "Buenos Aires";
    "France ", "Paris";
    "Switzerland", "Bern"
  ]
  |> Map.ofList

Accessing

1: 
2: 
3: 
printfn "Employee number for Jeff: %d" employees.["Jeff"]
printfn "Capital of France is %s" capitals.["France"]
printfn "Does France have a capital? %b" (Map.containsKey "France" capitals)

Use TryFind to return an Option type with the value if found:

1: 
2: 
3: 
match Map.tryFind "Joe" employees with
| Some number -> printfn "Employee found, ID: %d" number
| None -> printfn "Employee not found"

Map Module

Functions that operate on a Map: