Skip to content

Instantly share code, notes, and snippets.

@maximveksler
Last active January 2, 2017 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximveksler/a26c11df98452886011a05834d688090 to your computer and use it in GitHub Desktop.
Save maximveksler/a26c11df98452886011a05834d688090 to your computer and use it in GitHub Desktop.
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)
}
@maximveksler
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment