Last active
December 22, 2015 23:49
-
-
Save isaacabraham/6549316 to your computer and use it in GitHub Desktop.
Demonstrates a simple generate memoize function in F#
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
// Raw add function | |
let add (x,y) = x + y | |
// Memoized version | |
let add = memoize add | |
add (5,10) // Adding (5,10) to cache | |
add (5,10) // Cache hit for (5,10) |
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
let memoize(code) = | |
let cache = Dictionary() | |
fun input -> | |
let resultIsCached,result = cache.TryGetValue(input) | |
if resultIsCached then | |
printfn "cache hit for %A" input | |
result | |
else | |
let result = code(input) | |
printfn "adding %A to cache" input | |
cache.[input] <- result | |
result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment