Created
June 8, 2015 15:44
-
-
Save naoty/c487629cd931a452bbb5 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
| import Foundation | |
| enum MaybeInt { | |
| case Nothing | |
| case Just(Int) | |
| } | |
| extension MaybeInt : Printable { | |
| var description : String { | |
| switch self { | |
| case .Nothing: | |
| return "Nothing" | |
| case .Just(let x): | |
| return "\(x)" | |
| } | |
| } | |
| } | |
| infix operator >>= { associativity left precedence 120 } | |
| func >>= (left: MaybeInt, right: (Int -> MaybeInt)) -> MaybeInt { | |
| switch left { | |
| case .Nothing: | |
| return .Nothing | |
| case .Just(let x): | |
| return right(x) | |
| } | |
| } | |
| let result1 = MaybeInt.Just(1) >>= { x in return MaybeInt.Just(x + 1) } | |
| println(result1) //=> "2" | |
| let result2 = MaybeInt.Just(1) >>= { x in return MaybeInt.Just(x + 1) } >>= { _ in return MaybeInt.Nothing } | |
| println(result2) //=> "Nothing" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment