Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapM putStrLn ["a", "b"] why does it show three lines?

Tags:

io

haskell

monads

Prelude> mapM putStrLn ["a", "b"]
a
b
[(),()]
Prelude> mapM_ putStrLn ["a", "b"]
a
b

Why first version shows third line and second does not and where does third line comes from. I would not expect it.

like image 602
Trismegistos Avatar asked Dec 04 '22 01:12

Trismegistos


1 Answers

If you put the mapM version in a standalone program, compile it with ghc, and run it, you don't get a third line from it, either:

$ cat demo.hs
main = mapM putStrLn [ "a", "b" ]
$ ghc demo.hs
$ ./demo
a
b
$

That [(),()] you see in ghci is just the return value of the mapM call; ghci automatically displays the value of every expression you enter. (This is why ghci is called a Read-Evaluate-Print Loop, or REPL; the "Print" part is what you're seeing here.)

While mapM creates a list containing the return value of every putStrLn call (so you get one () for each element in the list), mapM_ discards those return values and returns IO (), which ghci doesn't bother to display. So you don't see an extra line from ghci in that case.

like image 166
Mark Reed Avatar answered Dec 27 '22 06:12

Mark Reed