Last active
January 2, 2017 13:11
-
-
Save maximveksler/a26c11df98452886011a05834d688090 to your computer and use it in GitHub Desktop.
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
func memoize<T: Hashable, U>(work: @escaping ((T)->U, T) -> U) -> (T)->U { | |
var memo = Dictionary<T, U>() | |
func wrap(x: T)->U { | |
if let q = memo[x] { return q } | |
let r = work(wrap, x) | |
memo[x] = r | |
return r | |
} | |
return wrap | |
} | |
let factorial = memoize { | |
factorial, x in | |
x == 0 ? 1 : x * factorial(x-1) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See related post https://medium.com/@mvxlr/swift-memoize-walk-through-c5224a558194#.g1fowcm1m