Skip to content

Instantly share code, notes, and snippets.

@mrange
Last active October 3, 2016 09:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrange/e76b90ced507c4685e59d0744a89d61d to your computer and use it in GitHub Desktop.
Save mrange/e76b90ced507c4685e59d0744a89d61d to your computer and use it in GitHub Desktop.
Latebinding in F# using ? operator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment