Saturday, 14 May 2016

Haskell: print Vs putStrLn


Haskell provides putStr, putStrLn functions, which write given string to standard output (terminal). putStr, putStrLn are almost same, only difference is putStrLn adds a newline character.
Prelude> :t putStr
putStr :: String -> IO ()
Prelude> 
Prelude> :t putStrLn
putStrLn :: String -> IO ()

print function displays value of any printable type to the standard output device. print function do this by calling show on its input first.

Technically print is defined like below.

print x = putStrLn (show x)
*Main> :t print
print :: Show a => a -> IO ()


Observe the signature of print function, it takes an argument ‘a’ which type should be instance of type class Show and return to IO.
*Main> print 10
10
*Main> 
*Main> print [1, 2, 3]
[1,2,3]
*Main> 
*Main> print 10.01
10.01
*Main> 


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



Previous                                                 Next                                                 Home

No comments:

Post a Comment