Last active
August 29, 2015 14:24
-
-
Save hiroshi-maybe/2034d41406b2ec3666c8 to your computer and use it in GitHub Desktop.
Maybe monad written in Swift
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
| // from Swiftz | |
| public class K1<A> { public init() {} } | |
| protocol Monad { | |
| typealias A | |
| typealias B | |
| typealias FB = K1<B> | |
| func bind(A -> FB) -> FB; | |
| static func ret(A) -> Self | |
| } | |
| enum Maybe<T> : Monad { | |
| case Just(T) | |
| case Nothing | |
| typealias A = T | |
| typealias B = Any | |
| typealias FB = Maybe<B> | |
| // crash!! with `typealias K1 = Maybe` | |
| func bind<B>(f:T -> Maybe<B>) -> Maybe<B> { | |
| switch self { | |
| case .Just(let x): return f(x) | |
| default: return .Nothing | |
| } | |
| } | |
| // compile error happens without `return`!! | |
| static func ret(a:A) -> Maybe<A> {return .Just(a)} | |
| } | |
| let one = Maybe<Int>.ret(1) | |
| let res = one.bind({(x:Int) in .Just(x+2)}) | |
| .bind({(_:Int) in .Nothing}) // needs (_:Int) for type inference | |
| .bind({(x:Int) in .Just(x*2)}) | |
| switch res { | |
| case Maybe<Int>.Just(let x): print("\(x)") | |
| default: print("nothing") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment