Created
May 13, 2015 12:37
-
-
Save nickleeh/cfe98119e255141745a2 to your computer and use it in GitHub Desktop.
Memoizing pure functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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