Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Last active August 29, 2015 14:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/58e61d492fd09efe3d9d to your computer and use it in GitHub Desktop.
Save natecook1000/58e61d492fd09efe3d9d to your computer and use it in GitHub Desktop.
Memoized Fibonnaci series
// 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