If conditional statements are used to execute code blocks based on a conditional expression. Haskell provides the if then else keywords to achieve conditional statement execution.
Haskell’s language provides the following conditional statement types
- if then else statements
- nested if else statements
Haskell if conditional statement
Here is an example
if Condition then codeblock1 else codeblock2
Condition is a Haskell expression that evaluates boolean values. if the condition is true, codeblock1 is executed, else codeblock2 is executed.
In the below example, the variable is initialized with zero, In the if conditional expression, the variable is compared with zero value, if it is true, then the block is executed, otherwise else block is executed.
main = do
let number = 0
if number == 0
then putStrLn "Number is Zero"
else putStrLn "Number is not Zero"
Output:
Number is Zero
Haskell Nested if else statements.
Nested if else types are written if else block inside another if statement
Here is a syntax
if condition1
then block1
else if condition2
then block2
ese block3
If the condition is true, block1 code is executed. Otherwise, condition2 is false, block2 will execute. Else block3 will execute.
Here is an example nested if else statement
main = do
let number = 11
if number == 0
then putStrLn "Number is zero"
else signum number = if number < 0
then putStrLn "Number is Negative"
else putStrLn "Number is Positive"
Output:
Number is Positive