Created
August 17, 2014 06:50
-
-
Save tel/8e7627e1bce8c5d356f4 to your computer and use it in GitHub Desktop.
Maybe in Swift
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
enum Maybe<A> { | |
case Nothing, Just(A) | |
func map<B> (f: A -> B) -> Maybe<B> { | |
switch self { | |
case .Nothing: return .Nothing | |
case .Just(let a): return .Just(f(a)) | |
} | |
} | |
func andThen<B> (f: A -> Maybe<B>) -> Maybe<B> { | |
switch self { | |
case .Nothing: return .Nothing | |
case .Just(let a): return f(a) | |
} | |
} | |
func withDefault(def: A) -> A { | |
switch self { | |
case .Nothing: return def | |
case .Just(let a): return a | |
} | |
} | |
} | |
func liftMay2<A,B,C>(f: (A, B) -> C, m1: Maybe<A>, m2: Maybe<B>) -> Maybe<C> { | |
return m1.andThen({a in return m2.andThen({b in return .Just(f(a, b))}) }) | |
} | |
liftMay2(+, .Just(3), .Just(4)).withDefault(0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment