Last active
April 6, 2016 04:40
-
-
Save cobbal/7562875ab5bfc6f0aed6 to your computer and use it in GitHub Desktop.
Monad protocol in swift
This file contains hidden or 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
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