Skip to content

Instantly share code, notes, and snippets.

@naoty
Created June 8, 2015 15:44
Show Gist options
  • Select an option

  • Save naoty/c487629cd931a452bbb5 to your computer and use it in GitHub Desktop.

Select an option

Save naoty/c487629cd931a452bbb5 to your computer and use it in GitHub Desktop.
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