Skip to content

Instantly share code, notes, and snippets.

@cobbal
Last active April 6, 2016 04:40
Show Gist options
  • Save cobbal/7562875ab5bfc6f0aed6 to your computer and use it in GitHub Desktop.
Save cobbal/7562875ab5bfc6f0aed6 to your computer and use it in GitHub Desktop.
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