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 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"
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 executes. else block3 will executes.
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"
Number is Positive