0 then putStrLn "Hello" putStrLn "Anything" I want to have "two assertio...">

Haskell if then with "two statements"

How to do it:

if n > 0
then putStrLn "Hello"
     putStrLn "Anything"

      

I want to have "two assertions" in one condition, but I keep getting compilation errors

I tried to use half a line with no luck

+3


source to share


2 answers


then

can only take one value. But you're in luck because it do

splits multiple values IO()

into one ....

if n > 0
  then do
    putStrLn "Hello"
    putStrLn "Anything"
  else return ()

      



Remember, in Haskell, you also need else

(and return ()

create a trivial IO()

one that does nothing).

+16


source


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")

      

+4


source







All Articles