Maps in F#

Based on the given instruction, here’s the Go code example translated into F# along with the appropriate explanations in Markdown format suitable for Hugo.


Maps are F#’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use:

let m = Map.empty<string, int>

Set key/value pairs using typical map.[key] = value syntax.

let m = m.Add("k1", 7).Add("k2", 13)

Printing a map with printfn will show all of its key/value pairs.

printfn "map: %A" m

Get a value for a key with map.[key].

let v1 = m.["k1"]
printfn "v1: %d" v1

If the key doesn’t exist, an exception is thrown. It’s safer to use tryFind which returns an Option type.

let v3 = m |> Map.tryFind "k3"
printfn "v3: %A" v3

The Map.count returns the number of key/value pairs when called on a map.

printfn "len: %d" (Map.count m)

To remove a key/value pair from a map, use Map.remove.

let m = m |> Map.remove "k2"
printfn "map: %A" m

To remove all key/value pairs from a map, use Map.empty.

let m = Map.empty<string, int>
printfn "map: %A" m

The optional second return value when getting a value from a map using tryFind indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0 or "".

let prs = m |> Map.tryFind "k2" |> Option.isSome
printfn "prs: %b" prs

You can also declare and initialize a new map in the same line with this syntax.

let n = Map.ofList [("foo", 1); ("bar", 2)]
printfn "map: %A" n

The Map module contains a number of useful utility functions for maps.

let n2 = Map.ofList [("foo", 1); ("bar", 2)]
if n = n2 then
    printfn "n == n2"

Note that maps appear in the form [k, v; k, v] when printed with printfn.

$ fsharpi maps.fsx
map: [("k1", 7); ("k2", 13)]
v1: 7
v3: None
len: 2
map: [("k1", 7)]
map: []
prs: false
map: [("bar", 2); ("foo", 1)]
n == n2

Next example: Functions.


This translation leverages F#’s idiomatic features such as Map functions and pattern matching.