Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Haskell : >>= : Use result of first IO action in second


By using (>>=), we can use the result of first IO action in second IO action.
Prelude> :t (>>=)
(>>=) :: Monad m => m a -> (a -> m b) -> m b


Sample.hs
square :: Integer -> Integer
square x = (x*x)

main = putStrLn "Enter a number"
>> readLn
>>= \x -> putStrLn ("Square of " ++ (show x) ++ " is " ++ show (square x))

$ ghc Sample.hs
[1 of 1] Compiling Main ( Sample.hs, Sample.o )
Linking Sample ...
$
$ ./Sample
Enter a number
10
Square of 10 is 100


All the statements in the do block are internally combined using >>, >>=.

Sample.hs
main = 
do
putStrLn "'Enter a Number"
a <- readLn
print (a==10)


Above code snippet is translated like below.

Sample.hs


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Haskell : >>= : Use result of first IO action in second

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×