Skip to content

Instantly share code, notes, and snippets.

@zats
Created December 6, 2014 22:03
Show Gist options
  • Save zats/178d829fed1242b27694 to your computer and use it in GitHub Desktop.
Save zats/178d829fed1242b27694 to your computer and use it in GitHub Desktop.
Dinamyc programming.swift
func memoize<T: Hashable, U>( body: ((T)->U, T)->U ) -> (T)->U {
var memo = Dictionary<T, U>()
var result: ((T)->U)!
result = { x in
if let q = memo[x] { return q }
let r = body(result, x)
memo[x] = r
return r
}
return result
}
let factorial = memoize { factorial, x in x == 0 ? 1 : x * factorial(x - 1) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment