Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between (>>=) and (>=>)

I need some clarification regarding (>>=) and (>=>).

*Main Control.Monad> :type (>>=)                                                                                                                                                               
(>>=) :: Monad m => m a -> (a -> m b) -> m b                                                                                                                                                
*Main Control.Monad> :type (>=>)                                                                                                                                                               
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c 

I know about bind operator(>>=) but I am not getting the context where (>=>) is useful. Please explain with simple toy example.

Edit : Correcting based on @Thomas comments

like image 576
venu gangireddy Avatar asked Aug 22 '16 13:08

venu gangireddy


1 Answers

The (>=>) function is kind of like (.), but instead of working with a -> b, it works with a -> m b.

-- Ask the user a question, get an answer.
promptUser :: String -> IO String
promptUser s = putStrLn s >> getLine

-- note: readFile :: String -> IO String

-- Ask the user which file to read, return the file contents.
readPromptedFile :: String -> IO String
readPromptedFile = promptUser >=> readFile

-- Ask the user which file to read,
-- then print the contents to standard output
main = readPromptedFile "Read which file?" >>= putStr

This is a bit contrived but it illustrates (>=>). Like (.), you don't need it, but it is generally useful for writing programs in the point-free style.

Note that (.) has the opposite argument order from (>=>), but there is also (<=<) which is flip (>=>).

readPromptedFile = readFile <=< promptUser
like image 56
Dietrich Epp Avatar answered Oct 13 '22 16:10

Dietrich Epp