Skip to content

Instantly share code, notes, and snippets.

@stefanalfbo
Created February 29, 2012 22:04
Show Gist options
  • Save stefanalfbo/1944805 to your computer and use it in GitHub Desktop.
Save stefanalfbo/1944805 to your computer and use it in GitHub Desktop.
Simple F# memoization
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