Haskell if then with "two statements"
Your example doesn't make sense in Haskell. Every expression must have a value, so you always need to have else
, even if it's simple return ()
.
Since it must be one expression, you cannot just do
putStrLn "Hello"
putStrLn "Anything"
since they are two expressions of type IO ()
, which means that it is a evaluator with some external effects and that there is no result. You have two calculations to run in sequence, which can be done with the combinator>>
putStrLn "Hello" >> putStrLn "Anything"
There is also an alternative syntax using a block do
.
do
putStrLn "Hello"
putStrLn "Anything"
It is important to note that this will compile with the same code >>
as in the example above. A block do
can be thought of as syntactic sugar (there is more to it, but for simplicity, you can think of it that way.)
Putting it all together, we
if n > 0
then putStrLn "Hello" >> putStrLn "Anything"
else return ()
or using the do block
if n > 0
then do
putStrLn "Hello"
putStrLn "Anything"
else return ()
Since this pattern is quite common, there is a combinator when
(in Control.Monad
) that does exactly this
when (n > 0)
do
putStrLn "Hello"
putStrLn "Anything"
or just just
when (n > 0) (putStrLn "Hello" >> putStrLn "Anything")
source to share