Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Last active February 8, 2017 02:10
Show Gist options
  • Select an option

  • Save ukitaka/39eacb94f4ccf1493fa46e3f7f6cf50d to your computer and use it in GitHub Desktop.

Select an option

Save ukitaka/39eacb94f4ccf1493fa46e3f7f6cf50d to your computer and use it in GitHub Desktop.
Recoverable
func const<A, B>(_ a: A) -> (B) -> A {
return { _ in a }
}
struct LazyRecoverable<A> {
private let original: A
private var updatef: ((A) -> A)?
private var mutableCopy: A
init(_ original: A) {
self.original = original
self.mutableCopy = original
}
mutating func update(_ f: @escaping (A) -> A) {
if let updatef = self.updatef {
self.mutableCopy = updatef(mutableCopy)
}
self.updatef = f
}
func commit() -> A {
let f = updatef ?? const(mutableCopy)
return f(mutableCopy)
}
func rollback() -> A {
return original
}
}
struct Recoverable<A> {
private let original: A
private var mutableCopy: A
init(_ original: A) {
self.original = original
self.mutableCopy = original
}
mutating func update(_ f: (A) -> A) {
self.mutableCopy = f(mutableCopy)
}
func commit() -> A {
return mutableCopy
}
func rollback() -> A {
return original
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment