Created
April 17, 2015 20:37
-
-
Save toby/1c42be3d0a6ed0753560 to your computer and use it in GitHub Desktop.
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
// 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