Why does \n not print a new line in Haskell?

A common confusion that arises when using the Glasgow Haskell Compiler is that the \n character does not print a new line in Haskell, unlike in other languages.

The code below illustrates the issue:

main = print ("line1\nline2")

The \n character is printed as part of the output in the above code, instead of printing a new line.

Haskell’s print function does not evaluate escape sequences such as \n, so the entire expression line1\nline2 is an output.

To print a new line, we can instead use the putStr() function, which will evaluate the escape sequence. This is shown below:

main = putStr ("line1\nline2")

The putStr() function evaluates escape characters. So, line1 and line2 appear on separate lines, and the output also does not contain quotation marks. This is unlike when we used the print function.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources