Tuesday 10 May 2016

Haskell: putStr, putStrLn: Write string to standard output


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 ()

See the IO (), in above functions signature, Whenever you see IO () in function signature, you can assume that the function may have side affects. You may ask me  what is (), in IO (), it represent empty tuple, it indicates that there is no return value from putStrL putStrLn functions.


Sample.hs
main = do
        putStrLn "Enter Your Name : "
        name <- getLine
        putStrLn ("Hello " ++  name)

$ ghc Sample.hs
$ ./Sample
Enter Your Name : 
Krishna
Hello Krishna


Prelude> :t getLine
getLine :: IO String

name <- getLine
getLine performs IO action, The <- operator is used to “pull out” the result from performing an I/O action and store it in a variable.

You can avoid parenthesis using $ operator. Anything appearing after it will take precedence over anything that comes before. You can rewrite above program using $ operator like below.

Sample.hs

main = do
        putStrLn "Enter Your Name : "
        name <- getLine
        putStrLn $ "Hello " ++  name


How to display non-string data to console ?
You can display non string data to console like ‘putStrLn (show data)’ statement.

*Main> putStrLn (show 10)
10
*Main> 
*Main> putStrLn (show [1, 2, 3])
[1,2,3]
*Main> 
*Main> putStrLn (show 10.01)
10.01


In addition to putStrLn, Haskell provides print function which is equivalent of ‘putStrLn (show)’ statement.

print x = putStrLn (show x)
*Main> print 10
10
*Main> 
*Main> print [1, 2, 3]
[1,2,3]
*Main> 
*Main> print 10.01
10.01
*Main> 




Previous                                                 Next                                                 Home

No comments:

Post a Comment