Last active
August 22, 2021 06:03
-
-
Save Koshimizu-Takehito/d3129e0c80b7b847a9814804554ed583 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
/// | |
/// ```swift | |
/// let fibonacci = memoize { (function: (Int) -> Int, n: Int) -> Int in | |
/// if n < 2 { | |
/// return n | |
/// } | |
/// return function(n - 1) + function(n - 2) | |
/// } | |
/// ``` | |
/// | |
/// ```swift | |
/// let factorial = memoize { (function: (Int) -> Int, n: Int) -> Int in | |
/// if n < 2 { | |
/// return 1 | |
/// } | |
/// return n * function(n-1) | |
/// } | |
/// ``` | |
func memoize<T: Hashable, U>(body: @escaping(((T) -> U), T) -> U) -> (T) -> U { | |
var memo = [T: U](), function: ((T) -> U)! | |
function = { x in | |
memo[x] ?? { | |
let r = body(function, x) | |
memo[x] = r | |
return r | |
}() | |
} | |
return function | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment