Created
July 2, 2014 01:55
-
-
Save tLewisII/bfee33f69ddb8e03b379 to your computer and use it in GitHub Desktop.
Try at a Reader 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
//this is a playground | |
struct Reader<R,A> { | |
let f:R -> A | |
init(_ fun:R -> A) { | |
f = fun | |
} | |
static func wrap(val:A) -> Reader<R,A> { | |
return Reader({_ in val}) | |
} | |
func runReader(r:R) -> A { | |
return f(r) | |
} | |
} | |
func >>=<R,A,B>(w:Reader<R,A>, f:(R -> A) -> Reader<R,B>) -> Reader<R,B> { | |
return f({(env:R) in w.runReader(env)}) | |
} | |
func hello() -> Reader<String, String> { | |
return Reader({name in "Hello \(name)!"}) | |
} | |
func bye() -> Reader<String, String> { | |
return Reader({name in "Bye \(name)!"}) | |
} | |
func both() -> Reader<String,String> { | |
return Reader({name in hello().runReader(name) + " " + bye().runReader(name)}) | |
} | |
both().runReader("terry") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment