Tuesday 10 May 2016

Haskell: Standard Input Output functions

Almost all real world applications interact with outside world. For example, your application may need to get data from some socket, read information from some URL, input from user, write data to some socket, send mail etc., Haskell provides wide variety of I/O handling functions, which makes your task easier.


Sample.hs
welcome name = "Hello " ++ name ++ ". Welcome to Haskell world!"

main = do
        putStrLn "Please tell me your name"
        name <- getLine
        
        let info = welcome name
        putStrLn info


Above program takes some input from user and welcome message to terminal. ‘welcome name’ is a pure function, it always produces the same result when given the same parameters, and never has side affects. Where as ‘main’ is impure function, it may produce different results for the same parameters and may have side affects.

$ runghc Sample.hs
Please tell me your name
Krishna
Hello Krishna. Welcome to Haskell world!


Following table summarizes standard IO functions.
Function
Description
Write string to standard output
Write string to standard output
Return nothing from IO action
Write a character to the standard output
print data to console
Read line from standard input
Read character
Interact with input
  
Note
a.   You can only perform IO action from within other IO actions.
b.   When you’re working in a do block, use <- to get results from IO actions and let to get results from pure code. When used in a do block, you should not put in after your let statement.




Previous                                                 Next                                                 Home

No comments:

Post a Comment