Last active
February 7, 2017 02:16
-
-
Save zlangley/51fdec10f89eeeafa49f to your computer and use it in GitHub Desktop.
Memoize 1-parameter functions. Saw something like this in the Advanced Swift WWDC talk. Tried to reproduce it.
This file contains hidden or 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
func memoize<T: Hashable, U>(f: ((T -> U), T) -> U) -> (T -> U) { | |
var cache = [T: U]() | |
var memoized: (T -> U)! | |
memoized = { n in | |
if cache[n] == nil { | |
cache[n] = f(memoized, n) | |
} | |
return cache[n]! | |
} | |
return memoized | |
} | |
let fibonacci: (Int -> Int) = memoize { | |
f, n in return (n == 0 || n == 1) ? n : f(n - 1) + f(n - 2) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment