Last active
April 2, 2017 19:19
-
-
Save maximveksler/3d4deca1912870bdb142a1ce27adcd71 to your computer and use it in GitHub Desktop.
memoize implementation using swift 3
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
// Non Recursive | |
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
See related post https://medium.com/@mvxlr/swift-memoize-walk-through-c5224a558194#.g1fowcm1m