Skip to content

Instantly share code, notes, and snippets.

@juandesant
Forked from sforteln/MemoizationWithGenerics
Last active April 24, 2020 09:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juandesant/fda9cc851470a25e3cf37210dd2251f8 to your computer and use it in GitHub Desktop.
Save juandesant/fda9cc851470a25e3cf37210dd2251f8 to your computer and use it in GitHub Desktop.
Simple Swift Function to memoize generic functions of the form T -> U
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)
@juandesant
Copy link
Author

Please note that this does not work well for memoizing the fibonacci function because it is recursive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment