Skip to content

Instantly share code, notes, and snippets.

@tLewisII
Created July 2, 2014 01:55
Show Gist options
  • Save tLewisII/bfee33f69ddb8e03b379 to your computer and use it in GitHub Desktop.
Save tLewisII/bfee33f69ddb8e03b379 to your computer and use it in GitHub Desktop.
Try at a Reader Monad in Swift
//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