Created
July 4, 2017 13:26
-
-
Save sforteln/15b24f12d55fda37033bdff1544a1d62 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 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