Skip to content

Instantly share code, notes, and snippets.

@tel
Created August 17, 2014 06:50
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 tel/8e7627e1bce8c5d356f4 to your computer and use it in GitHub Desktop.
Save tel/8e7627e1bce8c5d356f4 to your computer and use it in GitHub Desktop.
Maybe in Swift
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