Skip to content

Instantly share code, notes, and snippets.

@sforteln
Created July 4, 2017 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sforteln/15b24f12d55fda37033bdff1544a1d62 to your computer and use it in GitHub Desktop.
Save sforteln/15b24f12d55fda37033bdff1544a1d62 to your computer and use it in GitHub Desktop.
Simple Swift Function to memoize generic functions of the form T -> U
func memoize<T: Hashable,U>(function: @escaping (T) -> U) -> (T) -> U{
var cache : [T:U] = [:]
func memoWrapper(input: T) -> U {
if let cacheValue = cache[input] {
print("used cached result")
return cacheValue
}
let newVal = function(input)
cache[input] = newVal
print("new result")
return newVal
}
return memoWrapper
}
func square(_ input: Int) -> Int {
return input * input
}
let memoSquare = memoize(function: square)
memoSquare(2)
memoSquare(2)
memoSquare(3)
memoSquare(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment