Created
December 6, 2014 22:03
-
-
Save zats/178d829fed1242b27694 to your computer and use it in GitHub Desktop.
Dinamyc programming.swift
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>( 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