Created
February 29, 2012 22:04
-
-
Save stefanalfbo/1944805 to your computer and use it in GitHub Desktop.
Simple F# memoization
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 | |
// A simple function with some built in delay | |
// val square : int -> int | |
let square x = | |
System.Threading.Thread.Sleep(x * 1000) | |
x * x | |
// A generic memoization function that takes a function with one parameter | |
// val memoization : ('a -> 'b) -> ('a -> 'b) when 'a : equality | |
let memoization (f: 'a -> 'b) = | |
// Storage for the calculated result | |
let cache = new Dictionary<_, _>() | |
// Check if it's in the cache or not | |
(fun x -> | |
match cache.TryGetValue(x) with | |
| true, cachedValue -> cachedValue | |
| _ -> | |
let result = f x | |
cache.Add(x, result) | |
result) | |
// Try the memoization function | |
let memoSquare = memoization square | |
// Run it in the F# interactive with: #time;; | |
memoSquare 3 | |
// and one more time | |
memoSquare 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment