Friday, 29 April 2016

Haskell: do block

If you want to evaluate multiple IO operations you should keep them in do block.
Sample.hs
main = do
        putStrLn "Hello Haskell"
        putStrLn "I am very exited to explore you"
        putStrLn "Let me run this IO program"

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$
$ ./Sample
Hello Haskell
I am very exited to explore you
Let me run this IO program
putStrLn writes string to terminal. Reading output of an IO function is little different than simple assignment. You should use <- operator, to read data from IO function. For example, getLine function reads some data from user.
Sample.hs
main = do
        putStrLn "Enter your name: "
        name <- getLine
        putStrLn ("Hello " ++ name)

$ ghc Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, Sample.o )
Linking Sample ...
$
$ ./Sample
Enter your name: 
Hari Krishna
Hello Hari Krishna


What about getting data from Non-IO functions in do block?
By using let statemet, you can read data from Non-IO function.

Sample.hs

square :: Integer -> Integer
square x = x*x

main = do
        putStrLn "Enter a number "
        number <- getLine
        
        let x = (read number) :: Integer
        let result = square x

        putStrLn ("square of " ++ (show x) ++ " is " ++ (show result))


$ ghc Sample.hs
Linking Sample ...
$
$ ./Sample
Enter a number 
10
square of 10 is 100




Previous                                                 Next                                                 Home

No comments:

Post a Comment