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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With