Skip to content

Instantly share code, notes, and snippets.

@toby
Created April 17, 2015 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toby/1c42be3d0a6ed0753560 to your computer and use it in GitHub Desktop.
Save toby/1c42be3d0a6ed0753560 to your computer and use it in GitHub Desktop.
// Monads! >>= >> return
import Foundation
infix operator >>= { associativity left }
func >>=<A,B> (left: Optional<A>, right: A -> Optional<B>) -> Optional<B> {
if left == nil {
return nil
} else {
return right(left!)
}
}
// should be >> but Swift uses that for bitwise shift
infix operator >>> { associativity left }
func >>><A,B> (left: Optional<A>, right: Optional<B>) -> Optional<B> {
return left >>= { (_: A) -> Optional<B> in return right }
}
func excited(x: String) -> Optional<String>{
return Optional(x + "!")
}
func makeInt(x: String) -> Optional<Int> {
return x.toInt()
}
func doubleIt(x: Int) -> Optional<Int> {
return Optional(x + x)
}
// we need this because Playground doesn't support the Printable protocol :(
func toString(x: Int) -> Optional<String> {
return Optional(x.description)
}
let yay = Optional("yay")
let hey = Optional("hey")
let two = Optional(2)
let n:Optional<String> = nil
yay >>= excited >>= excited // Optional("yay!!")
yay >>= excited >>= excited >>> hey >>= excited // Optional("hey!")
n >>= excited >>= excited >>> hey >>= excited // nil
two >>= doubleIt >>= toString >>= excited // Optional("4!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment