Reputation: 375
How do you print Strings in Haskell with newline characters?
printString :: String -> String -> String -> String
printString s1 s2 s3 = (s1++"\n"++s2++"\n"++s3)
When using the function it prints the entire line including the newline characters as well
Upvotes: 1
Views: 10995
Reputation: 62808
Your printString
function does not print a string, it simply returns a string. Because you're running this in GHCi, it gets printed out. But it's GHCi that's printing it; your function itself prints nothing.
If you were to compile some code that calls printString
, you would discover that nothing gets printed.
By default, GHCi prints stuff as expressions. If you want to write the string to the console unaltered, you need to use putStrLn
, as the other answers suggest. Compare:
Prelude> print "1\n2"
"1\n2"
Prelude> putStrLn "1\n2"
1
2
Basically when you write an expression in GHCi, it automatically calls print
on the result if possible. Because if you're executing something, you probably want to see what the result was. Compiled code doesn't do this; it only prints what you explicitly tell it to.
Upvotes: 0
Reputation: 120711
As already commented, your code has nothing to do with printing. (It shouldn't have print in it's name either!) Printing is a side-effectful action (it makes something appear observably on your screen!) and hence can't be done without binding in the IO
type.
As for the actual task of generating a single three-line string, that is perfectly fulfilled by your suggested solution. "This\nis\ntest"
is a three-line string, as witnessed by
Prelude> lines $ printString "This" "is" "test"
["This","is","test"]
The reason why GHCi doesn't actually output three separate lines when you just write
Prelude> "This\nis\ntest"
"This\nis\ntest"
is that the print
function that's used for this purpose always guarantees a format that's safe to use again in Haskell code, hence it puts strings in quotes and escapes all tricky characters including newlines.
If you simply want to dump a string to the terminal as-is, use putStrLn
instead of print
.
Prelude> putStrLn $ printString "This" "is" "test"
This
is
test
Upvotes: 5
Reputation: 12060
In ghci, you can just type
putStrLn "line1\nline2"
If you want to write a program to do this, you need to make sure that putStrLn
runs in the IO monad, for instance, by putting it in main
main = do
<do stuff>
putStrLn "line1\nline2"
<do other stuff>
Upvotes: 1