Shorter way to conditionally "return ()" in a monad chain (>>, >>=) in Haskell?
haskell
Solution
`Control.Monad.unless` (and it's slightly more popular cousin, `when`) abstract this pattern out of your code:
import Control.Monad (unless)
main = do
line <- getLine
unless (line == "exit" || line == "quit") $ do
putStrLn line
main
-- or
when (line /= "exit" && line /= "quit") $ do
putStrLn line
main
A conditional `return ()` followed by unconditional code won't do the trick, as `return` is just a function, not a flow control keyword as in most other languages.
Problem
I have this simple code which reads a string and prints it, indefinitely. ``` main :: IO () main = getLine >>= putStrLn >> main ``` Now I want to exit after the `getLine` call if the line is either "quit" or "exit". My attempt: ``` main :: IO () main = do line <- getLine if line == "exit" || line == "quit" then return () else putStrLn line >> main ``` Doesn't look idiomatic to me. Is there a better way?