Question

Code:

main = do
  putChar 't'
  putChar 'e'
  putChar 'h'

While I run above-mentioned code, I am getting

*Main> main
teh*Main>

But I am expecting

*Main> main
teh
*Main>

My question: Why teh*Main comes instead of teh and then *Main in another line?

I am using emacs23 with haskell-mode.

Was it helpful?

Solution

putChar c writes just that one character to the console. That's what it's intended for. So unless you print a newline to the console afterward, whether with putChar, putStr or whatever other methods, the following output goes to the same line. The behaviour is the same as with C, or if you cat a file without trailing newline. It's ubiquitous. The only feasible alternative (it's unfeasible to check each output whether it ended with a newline) is to output a newline before the ghci or shell prompt unconditionally, which would lead to many annoying blank lines.

OTHER TIPS

If it really bothers you, you could always define

putCharLn :: Char -> IO ()
putCharLn c = do putChar c
                 putChar '\n'

Define main like:

main = do putChar 't'
          putChar 'e'
          putCharLn 'h'

And now:

*Main> main
teh
*Main> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top