Created
October 28, 2019 13:26
-
-
Save DanielCardonaRojas/af9e67e1ce2c99276957919581f326e2 to your computer and use it in GitHub Desktop.
Memoize
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>(work: @escaping (T)->U) -> (T)->U { | |
var memo = Dictionary<T, U>() | |
return { x in | |
if let q = memo[x] { return q } | |
let r = work(x) | |
memo[x] = r | |
return r | |
} | |
} | |
// Recursion supporting version | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment