Skip to content

Instantly share code, notes, and snippets.

@nickleeh
Created May 13, 2015 12:37
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 nickleeh/cfe98119e255141745a2 to your computer and use it in GitHub Desktop.
Save nickleeh/cfe98119e255141745a2 to your computer and use it in GitHub Desktop.
Memoizing pure functions
open System.Collections.Generic
let memoize (f : 'a -> 'b) =
let dict = new Dictionary<'a, 'b>()
let memoizedFunc (input : 'a) =
match dict.TryGetValue(input) with
| true, x -> x
| false, _ ->
// Evaluate and add to lookup table
let answer = f input
dict.Add(input, answer)
answer
// Return our memoized version of f dict is captured in the closure
memoizedFunc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment