Created
November 14, 2014 18:52
-
-
Save kconner/dfecaa5a26acf4c65f9b to your computer and use it in GitHub Desktop.
Memoization in Swift
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
class Memo<T> { | |
private let closure: () -> T; | |
private var result: T? | |
var value: T { | |
if let value = result { | |
return value | |
} else { | |
let value = closure() | |
println("computed \(value)") | |
result = value | |
return value | |
} | |
} | |
init(_ closure: () -> T) { | |
self.closure = closure | |
} | |
deinit { | |
println("memo destroyed") | |
} | |
func invalidate() { | |
result = nil | |
} | |
} | |
private func factorial(n: Int) -> Int { | |
if n <= 0 { | |
return 1 | |
} else { | |
return n * factorial(n - 1) | |
} | |
} | |
class Sample { | |
lazy var memo: Memo<Int> = Memo { [unowned self] in factorial(self.degree) } | |
var degree: Int = 3 { | |
didSet { | |
if degree != oldValue { | |
memo.invalidate() | |
} | |
} | |
} | |
init() {} | |
deinit { | |
println("memo owner destroyed") | |
} | |
} | |
var sample: Sample! = Sample() | |
println(sample.memo.value) | |
println(sample.memo.value) | |
println(sample.memo.value) | |
sample.degree = 20 | |
println(sample.memo.value) | |
println(sample.memo.value) | |
println(sample.memo.value) | |
sample.degree = 5 | |
println(sample.memo.value) | |
println(sample.memo.value) | |
println(sample.memo.value) | |
sample = nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment