Last active
October 16, 2015 19:03
-
-
Save dvanwinkle/9c156873905bf05ef32f to your computer and use it in GitHub Desktop.
Memoization in Swift
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
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