Skip to content

Instantly share code, notes, and snippets.

@mathonsunday
Created December 6, 2015 17:55
Show Gist options
  • Save mathonsunday/fde6a3358094fc925d87 to your computer and use it in GitHub Desktop.
Save mathonsunday/fde6a3358094fc925d87 to your computer and use it in GitHub Desktop.
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 ++ "!")
}
@cbarrett
Copy link

cbarrett commented Dec 6, 2015

You're on the right track I think, but your desugaring is not quite right. In Haskell the body of greeter desugars to:

ask >>= $ \name ->
    return ("hello, " ++ name ++ "!")

@cbarrett
Copy link

cbarrett commented Dec 6, 2015

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.

@mpurland
Copy link

mpurland commented Dec 9, 2015

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

@mpurland
Copy link

mpurland commented Dec 9, 2015

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