Last active
June 8, 2016 09:15
-
-
Save zhigang1992/5be3413e6c731dc38c1366c7ce99758e to your computer and use it in GitHub Desktop.
Lazy Monad
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
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