Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between print and putStrLn in Haskell

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 
like image 573
Amir Nabaei Avatar asked Oct 10 '13 06:10

Amir Nabaei


People also ask

What is the difference between print and putStrLn Haskell?

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.

What is print in Haskell?

It's an action that first outputs the first character and then outputs the rest of the string. print takes a value of any type that's an instance of Show (meaning that we know how to represent it as a string), calls show with that value to stringify it and then outputs that string to the terminal.


1 Answers

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.

like image 102
Chris Taylor Avatar answered Sep 20 '22 15:09

Chris Taylor