Created
December 6, 2015 17:55
-
-
Save mathonsunday/fde6a3358094fc925d87 to your computer and use it in GitHub Desktop.
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
First step is to desugar do notation. In this case we want to translate it to the bind (>>=) operator: | |
greeter = | |
name >>= ask | |
return ("hello, " ++ name ++ "!") | |
Now that it's desugared (not convinced I've done it correctly) I will translate it to Swift. | |
I'm relying on the Reader monad implementation in Swiftz (https://github.com/typelift/Swiftz/blob/968075391aedb15ec51ff9d5b7d4921b8fa3a3c6/Swiftz/Reader.swift) | |
Current code is: | |
func greeter(reader: Reader, name: String) { | |
name >>= Reader.ask | |
return ("hello, " ++ name ++ "!") | |
} |
So the Swift version would look like
Reader.ask().bind { name in
returnInReader("hello" + name + "!")
}
You could write Reader.ask() >>- { name in ... }
but I think the explicit bind
is a lot clearer, especially with trailing closure notation.
In the ReaderSpec this was the example that I gave:
func hello() -> Reader<String, String> {
return Reader { "Hello \($0)" }
}
/// could be used as
let greeting = hello().runReader("World")
// Output: Hello World
with syntactic sugar:
let greeting = (hello() >>- runReader)?("World")
// Output: Hello World
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You're on the right track I think, but your desugaring is not quite right. In Haskell the body of
greeter
desugars to: