Last active
August 29, 2015 14:06
-
-
Save hisui/54a7ddb4abe3d5f1af66 to your computer and use it in GitHub Desktop.
Monad in Swift
This file contains 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
// A trivial type just for this example | |
final class Id <A> { | |
let raw: A | |
init(_ a: A) { self.raw = a } | |
} | |
// A typeclass of the Monad | |
infix operator >>| { associativity left precedence 95 } | |
public protocol Monad { | |
typealias Elem | |
func >>| (fa: Self, f: Elem -> Self) -> Self /* (^_^;) ...? */ | |
class func pure(a: Elem) -> Self | |
} | |
// An instance of the Monad typeclass | |
extension Id: Monad { | |
typealias Elem = A // from Id<A> | |
class func pure(a: Elem) -> Id<A> { return Id(a) } | |
} | |
func >>| <A, B>(fa: Id<A>, f: A -> Id<B>) -> Id<B> { return f(fa.raw) } | |
// test | |
func pure<A, MA: Monad where MA.Elem == A>(a: A) -> MA { | |
return MA.pure(a) | |
} | |
let o = Id("(^_^)") >>| { pure($0.utf16Count) } >>| { pure(Double($0*$0)) } | |
println("\(o.raw)") // ==> 25.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment