News for hackers. Stuff that matters.
Re:IO Monad Considered Harmful by JoshTriplett on Friday January 23, 2015 @01:41AM (#8933675)
I've been writing Haskell code for years, and this is one of the most singularly useful articles I've read on it. I've certainly found the proliferation of "monad tutorials" and "learn this so you can print something" guides obnoxious, but it never occurred to me that IO really could be taught completely separately from monads.

Here's the outline of what the middle of a tutorial could look like, following this advice:

Here's how to print a string (putStr, putStrLn). Here's how to print something other than a string (show, print). Here's how to print two somethings in a row (>>). Here's how to read something and print that (>>=). Here's how to print something in a function other than main (:: IO ()). Here's how to read something in a function other than main (:: IO a, >>= again, return). Oh by the way, it turns out that pattern (return, >>=) is so common that Haskell gives it a special syntax (do notation). For instance, it works with the previously introduced Maybe. And with List. Remember typeclasses? You can write functions that work with IO, Maybe, and List (Monad m => ...).

Even when actually talking about monads, the explanation should come first, and the term should come later. "It turns out these operations are a common enough pattern that Haskell gives them special syntax..." comes across much more sanely than "now we're going to introduce something [complicated] called a monad".

Re:IO Monad Considered Harmful by millstone on Friday January 23, 2015 @02:20AM (#8933764)
I think your suggestion is a relative improvement over most tutorials. But it's still unmanageably hard.

"Here's how to read something and then print that: >>=". Sure, like `getLine >>= putStrLn`. Technically speaking, that's correct. But this doesn't generalize at all.

Maybe I want to greet the user by name. How do I read the name, prepend "Hello, " to it, and then print that? This is a totally natural thing to want to do, and is very straightforward in Java. But our Haskell newbie hits a wall - none of your cases cover it!

Here's how I might write that today, without using do notation: `getLine >>= (return . (++) "Hello, ") >>= putStrLn`. Look at that - it's totally nuts, and I would not attempt to explain that to a Haskell neophyte.

Using do-notation, you can make things nicer:

    do
     name <- getLine
     putStrLn $ "Hello, " ++ name
but this introduces a bunch of new syntax to learn: the difference between let-in and let and <-, how do-notation works, etc.

I don't have a better approach than what you suggest. I suspect that this stuff simply can't be made easy.

Re:IO Monad Considered Harmful by JoshTriplett on Friday January 23, 2015 @02:27AM (#8933788)
> Here's how I might write that today, without using do notation: `getLine >>= (return . (++) "Hello, ") >>= putStrLn`.

Don't write point-free code here. Here's a fairly simple version:

    getLine >>= \name -> putStrLn ("Hello, " ++ name)
The only novel thing there is the >>= operator itself. You don't even have to introduce return there; you can introduce return later.
Re:IO Monad Considered Harmful by rapala on Friday January 23, 2015 @02:45AM (#8933825)
Which can then be made to look exactly like the

  getLine >>= putStrLn
case by doing

  greet name = putStrLn ("Hello, " ++ name)
  main = getLine >>= greet
(Edited to include the definition of main)
Re:IO Monad Considered Harmful by ggchappell on Friday January 23, 2015 @02:54AM (#8933844)
This is a nice approach. Thanks to all of you in this thread. I think I'll try something like this when I introduce Haskell I/O in my Programming Languages class in a month or two.
Re:IO Monad Considered Harmful by millstone on Friday January 23, 2015 @03:22AM (#8933906)
If this is meant to be under main, you need a "let":

    main = do
      let greet name = putStrLn ("Hello, " ++ name)
      getLine >>= greet
For whatever reason, I didn't learn about the magic let syntax in do-notation until relatively late. Anyways this is very elegant, but not something I could have generated early on, especially because it mixes two different sequencing syntaxes (do-notation and >>=).
Re:IO Monad Considered Harmful by wz1000 on Friday January 23, 2015 @06:55AM (#8934425)
The 'do' is superfluous.

It would be much better as

    main = let greet name = putStrLn ("Hello, " ++ name)
                in getLine >>= greet
Re:IO Monad Considered Harmful by exDM69 on Friday January 23, 2015 @03:25AM (#8933909)
You can use "fmap" to make this nicer (but that introduces yet another concept). If you use hlint on the program above, you it will tell you to use fmap instead.

    fmap ("Hello, " ++) getLine >>= putStrLn
I learned this because hlint suggested it to me. Using hlint is a very good idea, even for beginners.

For a simple "greet" program, this isn't perhaps any neater or cleaner but fmap is a powerful tool with lots of practical uses.

Re:IO Monad Considered Harmful by millstone on Friday January 23, 2015 @02:36AM (#8933812)
Thanks, that's much better than what I wrote. Still I think that's a big jump for most programmers - it certainly was for me.
Re:IO Monad Considered Harmful by exDM69 on Friday January 23, 2015 @03:34AM (#8933927)
There's one thing that should be mentioned here: you can easily compose these things. You can do:

    echo = forever $ getLine >>= putStrLn
This also works with do notation, if you'd want to make the greet example looping.

    greetLoop = forever $ do
        name <- getLine
        putStrLn ("Hello, " ++ name)
This is a very powerful concept. In mainstream imperative programming languages, you can't assign "statements" to variables or return them from functions or pass them as parameters.
Re:IO Monad Considered Harmful by jeorgun on Friday January 23, 2015 @03:58AM (#8933988)
Maybe I'm misinterpreting you, but isn't that effectively what a closure is in an imperative language?

    def forever
      loop do yield end
    end

    forever do
      name = gets
      puts "Hello, name"
    end
or even

    template <typename F>
    void forever(const F& fn) { for (;;) fn(); }

    int main()
    {
      forever([]
      {
        std::string str;
        getline(std::cin, str);
        std::cout << "Hello, " << str << '\n';
      });
    }
looks a lot like the above code to me.
Re:IO Monad Considered Harmful by exDM69 on Friday January 23, 2015 @04:37AM (#8934059)
Well, in this simple example it is trivial to do the same by wrapping statements in a closure, but it's a bit more nuanced than that. But you still can't assign a for-loop as a value to a variable, for example (to exaggerate a little).

This becomes more apparent when using monads for non-IO applications like parsing. It's difficult (but not impossible, of course) to implement things like backtracking or non-determinism by writing lots of closures in an imperative programming language, they don't compose as nicely. There are parser combinator libraries (similar to Parsec) done in other languages of course, but some of them even implement monads in the language they work in. I recall seeing "class Monad" written in Python, I think it was in the pyparsec library.

Re:IO Monad Considered Harmful by dan00 on Friday January 23, 2015 @05:21AM (#8934161)
> getLine >>= (return . (++) "Hello, ") >>= putStrLn

A pointfree solution - if you want one - would be more in the form of:

    getLine >>= putStrLn . ("Hello, " ++)
It's really mostly about getting used reading pointfree style, but there's certainly an overuse of pointfree style in some Haskell code, then it gets pointless.
Re:IO Monad Considered Harmful by davedx on Friday January 23, 2015 @02:48AM (#8933833)
> getLine >>= (return . (++) "Hello, ") >>= putStrLn

And my coworkers yesterday were complaining that ClojureScript looked like Brainfuck...

(http://en.wikipedia.org/wiki/Brainfuck)

Re:IO Monad Considered Harmful by exDM69 on Friday January 23, 2015 @03:28AM (#8933915)
That's a very contrived example you obviously didn't spend any time trying to understand. No-one in their right mind would write code like that, except to demonstrate something.

And if you did write code like that, Haskell's hlint tool would make suggestions to turn it neat and readable using fmap.

Re:IO Monad Considered Harmful by pestaa on Friday January 23, 2015 @04:34AM (#8934051)
Why wouldn't I want to write that? Clearly you need a little practice before instantly recognizing a partially applied function where the next parameter will be appended to your other string, but that one-liner has actually a very nice computing flow.
Re:IO Monad Considered Harmful by exDM69 on Friday January 23, 2015 @04:52AM (#8934093)
That's a bit hard to read, isn't it? (return . f) is a common idiom (or antipattern?) which is better solved by using fmap. hlint will tell you this. For example:

    fmap ("Hello, " ++) getLine >>= putStrLn
This isn't necessarily better either, I'd write this using do-notation.

I understood every bit of that code, I just think it's ugly and hard to read and there are better ways to get the same done.

Re:IO Monad Considered Harmful by dllthomas on Friday January 23, 2015 @10:25AM (#8935254)
I don't like it because the flow of data keeps changing direction. I would prefer one of

    getLine >>= ( ("Hello, " ++) >>> putStrLn )

    putStrLn . ("Hello, " ++) =<< getLine
Re:IO Monad Considered Harmful by olavk on Friday January 23, 2015 @06:01AM (#8934259)
My take on how to explain basic IO without having to explain monads:

(1) Any function with interacts with the world is called an IO function and has the result type "IO something". e.g. "IO String" for getLine (because it returns a String). Functions and expressions which does not interact with the world are called 'pure'. IO is a type constructor, but for now it makes sense to think of it as a "tag" on result values which guarantees we cannot mix IO-functions with pure functions. If we could call IO functions inside pure functions, the whole idea of pure would dissolve. The IO "tag" allows the compiler to enforce that this can't happen.

(2) A function which calls IO functions uses 'do'-notation:

    somefun = do
	putStrLn "Hello"
	putStrLn "World"
Each line is a single IO function call (with arguments which are pure expressions). Each line in the do-block should be indented to the same level. (Only in the case where the function consist of just a single IO-call can the 'do' be left out, which is why you can write 'main = putStrLn "hello World"'). The do-notation guarantees that the operations are executed sequentially. The return value of the function is the return value of the last operation in the do-block.

If you want to use the return value of an IO function, you use a left-arrow (<-) to read it into a variable. Eg.

    somefun = do
        putStrLn "What is your name?"
	name <- getLine 
	putStrLn ("Hello, " ++ name)

Note that you cannot simplify the two lines to:

    X	putStrLn ("Hello, " ++ getLine)
The above breaks the rule that each IO function call have to be on a separate line in the do-block. IO-function calls can not be nested in expressions, they have to be sequential.

(3) Calling pure functions. You cannot call IO function from pure code, but you can call pure functions from IO-code. This is done via 'let':

    somefun = do
        putStrLn "What is your name?"
	name <- getLine 
	let name2 = reverse name
	putStrLn ("Olleh, , " ++ name2)
Note how the let syntax is distinctly different from the left-arrow syntax. The let syntax just assigns the result of a pure expression to a variable. The arrow syntax "extracts" a pure value from an IO value. The result of getLine is 'IO string' but the arrow "untags" it so the type of name is just "String", and it can be used as part of a pure expression.

(4) Returning pure values. The return type of a IO function has to be IO something. In the above example the return type is 'IO ()' since this is the result type of the last operation, putStrLn. But what if we want to return say the reversed name? The reversed name is a pure value, so this is will not compile:

    somefun = do
        putStrLn "What is your name?"
	name <- getLine 
	let name2 = reverse name
	putStrLn ("Olleh, " ++ name2)
    X	name2
We have to turn the String into an "IO String", because the result type of an IO function has to be "IO something". This is done with the "return" operation, which turns a pure value into the corresponding IO value. The name "return" is unfortunate since it looks equivalent to "return" in imperative languages. But in Haskell "return" doesn't actually exit the function. The function exits after the last operation regardless of the use of "return". The only thing "return" does is to "tag" a pure value so we can return it from an IO function:

    somefun = do
        putStrLn "What is your name?"
	name <- getLine 
	let name2 = reverse name
	putStrLn ("Olleh, " ++ name2)
   	return name2