In a statically typed language like F#
we work with types well-known at
compile-time. We consume external data sources in a type-safe manner using type
providers.
However, occassionally there's need to use late binding (like dynamic
in C#
).
For instance when working with JSON
documents that have no well-defined schema.
To simplify working with late binding F#
provides supports dynamic lookup operators ?
and ?<-
.
Example:
// (?) allows us to lookup values in a map like this: map?MyKey
let inline (?) m k = Map.tryFind k m
// (?<-) allows us to update values in a map like this: map?MyKey <- 123
let inline (?<-) m k v = Map.add k v m
let getAndUpdate (map : Map<string, int>) : int option*Map<string, int> =
let i = map?Hello // Equivalent to map |> Map.tryFind "Hello"
let m = map?Hello <- 3 // Equivalent to map |> Map.add "Hello" 3
i, m
It turns out that the F#
support for late binding is simple yet flexible.