Skip to content

Instantly share code, notes, and snippets.

@Koshimizu-Takehito
Last active August 22, 2021 06:03
Show Gist options
  • Save Koshimizu-Takehito/d3129e0c80b7b847a9814804554ed583 to your computer and use it in GitHub Desktop.
Save Koshimizu-Takehito/d3129e0c80b7b847a9814804554ed583 to your computer and use it in GitHub Desktop.
///
/// ```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