Haskell Sequencing Actions
Sequencing operators join IO actions so one runs after another without a do block. The >> operator runs two actions, and >>= passes the first result into the next step.
>> runs actions in order
The first putStrLn runs, then the second one runs. Both lines print.
main :: IO ()
main = putStrLn "First" >> putStrLn "Second">> keeps the second result
Two wrapped values run in order. Only the second value reaches print.
main :: IO ()
main = (return 10 >> return 32) >>= print>>= passes a result on
The typed line is Echo this. >>= hands that line straight to putStrLn.
main :: IO ()
main = getLine >>= putStrLnExample
main :: IO ()
main = do
getLine >>= putStrLn
line <- getLine
putStrLn lineKey points
- >>: an operator that runs two actions in order and keeps the result of the second one.
- First result dropped: with >>, the first action still runs, but its result is not kept.
- >>=: an operator that runs an action and passes its result into the next step.
- Next step: with >>=, the step after the operator is a function that takes that result.
- Same job, two forms: a short chain with >>= can also be written as a do block with <-.
- Order: in both operators, the action on the left runs first.
In this example, the typed lines are First echo and Second echo. The first line of the block uses >>= to pass the first typed line straight to putStrLn. The next two lines do the same job in do form, binding the line with <- before printing it.
Note
these operators work on plain values wrapped with return, not only on printing actions.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What does getLine >>= putStrLn do?