Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monad protocol in swift
protocol Monad {
typealias F
typealias U
class func bind<M : Monad where M.U == U>(Self, F -> M) -> M
class func `return`(F) -> Self
}
extension Array : Monad {
typealias F = T
typealias U = Array<()>
static func bind<M : Monad where M.U == U>(m : Array, _ f : F -> M) -> M {
var ret = Array<M.F>()
for a in m {
ret += f(a) as M.F[]
}
return ret as M
}
static func `return`(f : F) -> Array {
return [f]
}
}
operator infix >>= { associativity left }
func >>=<MA : Monad, MB : Monad where MA.U == MB.U>(lhs : MA, rhs : MA.F -> MB) -> MB {
return MA.bind(lhs, rhs)
}
println([3] >>= {[$0, $0 + 1]} >>= {[Double($0), Double(10 + $0)]})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.