Difference between print and putStrLn in Haskell
42,182
The function putStrLn
takes a String
and displays it to the screen, followed by a newline character (put a String followed by a new Line).
Because it only works with String
s, a common idiom is to take any object, convert it to a String
, and then apply putStrLn
to display it. The generic way to convert an object to a String
is with the show
function, so your code would end up with a lot of
putStrLn (show 1)
putStrLn (show [1, 2, 3])
putStrLn (show (Just 42))
Once you notice that, it's not a very big stretch to define a function that converts to a String
and displays the string in one step
print x = putStrLn (show x)
which is exactly what the print
function is.
Comments
-
Amir Nabaei almost 2 years
I am confused. I tried to use
print
, but I know people applyputStrLn
. What are the real differences between them?print $ function putStrLn $ function
-
CMCDragonkai almost 9 years
putStrLn
can show non ASCII characters like "я" whereasprint
cannot. I don't really know why though. TryputStrLn "я"
vsprint "я"
. -
Chris Taylor almost 9 years@CMCDragonkai It's for the reason I give in the answer. The
print
function callsputStrLn
on the output ofshow
, and theshow
functions converts strings to their unicode representation in order to display them. The unicode point for 'я' (Cyrillic letter "ya") is U+044F, or 1103 in decimal, which is whyshow "я"
outputs"\"\\1103\""
- this is what you would have to type in ghci to get the string composed of the seven characters"\1103"
(try it!) -
CMCDragonkai almost 9 yearsDoesn't this mean it would better to use
putStrLn
when working with text in general? -
Chris Taylor almost 9 yearsIf you have a
String
that you want to print to the screen, you should useputStrLn
. If you have something other than aString
that you want to print, you should useprint
. Look at the types!putStrLn :: String -> IO ()
andprint :: Show a => a -> IO ()
. -
Chris Taylor almost 9 yearsYou seem to be a bit confused. Literally the only difference between
putStrLn
andprint
is thatprint
callsshow
on its input first. Any difference between the result is because you have calledshow
on the input in one case, and not in the other. So when choosing which one to use, ask yourself - do I want to callshow
on the input or not? If the input is aString
then you almost certainly do not want to callshow
on it first.