Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save hiroshi-maybe/2034d41406b2ec3666c8 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/2034d41406b2ec3666c8 to your computer and use it in GitHub Desktop.
Maybe monad written in Swift
// 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