Skip to content

Instantly share code, notes, and snippets.

@dvanwinkle
Last active October 16, 2015 19:03
Show Gist options
  • Save dvanwinkle/9c156873905bf05ef32f to your computer and use it in GitHub Desktop.
Save dvanwinkle/9c156873905bf05ef32f to your computer and use it in GitHub Desktop.
Memoization in Swift
import Foundation
func perf<T, U>(f: T -> U) -> T -> (NSTimeInterval, U) {
return {
(a: T) -> (NSTimeInterval, U) in
let start = NSDate()
let result = f(a)
return (NSDate().timeIntervalSinceDate(start), result)
}
}
func memo<T: Hashable, U>(f: T -> U) -> T -> U {
var cache = [T:U]()
return {
(a: T) -> U in
var result = cache[a]
if result == nil {
result = f(a)
cache[a] = result
}
return result!
}
}
var fib: Int -> Double
fib = {
(n: Int) -> Double in
guard n > 0 else { return 0 }
guard n > 2 else { return 1 }
return fib(n-1) + fib(n-2)
}
let perfFib = perf(fib)
perfFib(20)
fib = memo(fib)
perfFib(20)
perfFib(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment