Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell writes '\n' instead of a newline

I have this code and instead of it printing out "\n", I want it to put the next string on a new line, but cannot seem to figure it out. Any pointers?

onSeparateLines :: [String] -> String
onSeparateLines [] = ""
onSeparateLines ( x:[] ) = x
onSeparateLines ( x:xs ) = x ++  "\n" ++ onSeparateLines xs

what I get is

"AAAA\nAAAA"

which should be:

"AAAA"
"AAAA"
like image 324
symon Avatar asked Oct 15 '15 17:10

symon


1 Answers

The given function and your use of "\n" are correct, so the error must be elsewhere. Without knowing the details, I suspect that you are using (the equivalent of) print rather than putStr to print your string. Make sure that your string is not being shown before it is printed.

If this is in GHCi, be aware that values are printed using print, so

> onSeparateLines ["foo", "bar"]

will print the string and show escaped characters. You want

> putStrLn (onSeparateLines ["foo", "bar"])

instead.

like image 69
Rein Henrichs Avatar answered Oct 30 '22 16:10

Rein Henrichs