Skip to content

Instantly share code, notes, and snippets.

@zhigang1992
Last active June 8, 2016 09:15
Show Gist options
  • Save zhigang1992/5be3413e6c731dc38c1366c7ce99758e to your computer and use it in GitHub Desktop.
Save zhigang1992/5be3413e6c731dc38c1366c7ce99758e to your computer and use it in GitHub Desktop.
Lazy Monad
enum Lazy<T> {
case Function(()->T)
case Value(T)
var value: T {
switch self {
case .Function(let f): return f()
case .Value(let v): return v
}
}
}
extension Lazy {
func flatMap<U>(function: T->Lazy<U>) -> Lazy<U> {
return Lazy<U>.Function({function(self.value).value})
}
func map<U>(function: T->U) -> Lazy<U> {
return self.flatMap({.Value(function($0))})
}
}
print(Lazy.Value(3).map({$0 + 1}).flatMap({ number in
.Function({"number:\(number)"})
}).value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment