Last active
August 29, 2015 14:06
-
-
Save natecook1000/58e61d492fd09efe3d9d to your computer and use it in GitHub Desktop.
Memoized Fibonnaci series
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
// this version of memoize is from the WWDC 2014 Advanced Swift session | |
// https://developer.apple.com/videos/wwdc/2014/?id=404 | |
func memoize<T: Hashable, U>(body: (T -> U, T) -> U ) -> (T) -> U { | |
var memo = [T: U]() | |
var result: (T -> U)! | |
result = { | |
value in | |
if let cached = memo[value] { return cached } | |
let toCache = body(result, value) | |
memo[value] = toCache | |
return toCache | |
} | |
return result | |
} | |
var fib = memoize { | |
(fib: Int -> Int, val: Int) -> Int in | |
return val == 1 || val == 0 ? 1 : fib(val - 1) + fib(val - 2) | |
} | |
let fib5 = fib(7) | |
// 21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment