Last active
August 29, 2015 14:02
-
-
Save gblazex/12b9310aec60e1ddc8c0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// JavaScript | |
function memoize(fn) { | |
var memo = {} | |
return function(x) { | |
return memo[x] || (memo[x] = fn(x)) | |
} | |
} | |
// Swift | |
func memoize<T: Hashable, U>( body: ((T)->U, T)->U ) -> (T)->U { | |
var memo = Dictionary<T, U>() | |
var result: ((T)->U)! | |
result = { x in | |
if let q = memo[x] { return q } | |
let r = body(result, x) | |
memo[x] = r | |
return r | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment