-
-
Save juandesant/fda9cc851470a25e3cf37210dd2251f8 to your computer and use it in GitHub Desktop.
Simple Swift Function to memoize generic functions of the form T -> U
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
func memoized<Input:Hashable,Output>(fn : @escaping (Input) -> Output) -> (Input)->Output { | |
var cache = [Input:Output]() | |
let function = fn | |
let closure = { | |
(val : Input) -> Output in | |
let value = cache[val] | |
if value != nil { | |
return value! | |
} else { | |
let newValue = function(val) | |
cache[val] = newValue | |
return newValue | |
} | |
} | |
return closure | |
} | |
func fibonacci(_ value:Int) -> Int { | |
var result = 0 | |
switch value { | |
case _ where value < 0: | |
result = 0 | |
case 0: | |
result = 0 | |
case 1,2: | |
result = 1 | |
default: | |
result = fibonacci(value-1) + fibonacci(value-2) | |
} | |
return result | |
} | |
let fastFibo = memoize(fibonacci) | |
fastFibo(90) | |
let fastSquare = memoize({(x:Int) -> Int in return x*x}) | |
fastSquare(900000) | |
fastSquare(900000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note that this does not work well for memoizing the fibonacci function because it is recursive.