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 Strings, 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.

Share:
42,182
Amir Nabaei
Author by

Amir Nabaei

Amir

Updated on July 05, 2022

Comments

  • Amir Nabaei
    Amir Nabaei almost 2 years

    I am confused. I tried to use print, but I know people apply putStrLn. What are the real differences between them?

    print $ function 
    putStrLn $ function
    
  • CMCDragonkai
    CMCDragonkai almost 9 years
    putStrLn can show non ASCII characters like "я" whereas print cannot. I don't really know why though. Try putStrLn "я" vs print "я".
  • Chris Taylor
    Chris Taylor almost 9 years
    @CMCDragonkai It's for the reason I give in the answer. The print function calls putStrLn on the output of show, and the show 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 why show "я" 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
    CMCDragonkai almost 9 years
    Doesn't this mean it would better to use putStrLn when working with text in general?
  • Chris Taylor
    Chris Taylor almost 9 years
    If you have a String that you want to print to the screen, you should use putStrLn. If you have something other than a String that you want to print, you should use print. Look at the types! putStrLn :: String -> IO () and print :: Show a => a -> IO ().
  • Chris Taylor
    Chris Taylor almost 9 years
    You seem to be a bit confused. Literally the only difference between putStrLn and print is that print calls show on its input first. Any difference between the result is because you have called show on the input in one case, and not in the other. So when choosing which one to use, ask yourself - do I want to call show on the input or not? If the input is a String then you almost certainly do not want to call show on it first.