If Then Else Expressions
Introduction: Making Decisions in Code
Welcome to Unit 6 of our 7-unit journey into Haskell! In our previous lesson, we learned how to keep complex calculations organized using local let and where bindings. Now, it is time to teach our programs how to make choices.
In the real world, we make decisions constantly based on specific conditions. For example, if a number is below zero, we might want to flip its sign to make it positive; otherwise, we leave it exactly as it is.
To handle simple, two-way decisions like this, Haskell provides the if/then/else syntax. It relies on a Bool (true or false) condition to decide which path your code should take. In this lesson, we will learn how to write these choices cleanly and safely.
Expressions and the Mandatory else
In many programming languages, an if statement is an action — it simply tells the computer to do something. However, in Haskell, if/then/else is an expression. This is a very important distinction. Just like the math expression 5 + 3 evaluates to the single value 8, a Haskell if expression evaluates to a single piece of data.
Let us build a function step by step to calculate the absolute (positive) value of an integer and see this in action. First, we write our type signature and define the function named absValue with a single input parameter, n.
Next, we introduce our condition using the if keyword. We want to check if n is less than zero.
Now, we must tell Haskell what value this expression should become if the condition is true. We do this using the then keyword. If n is less than zero, we will use the built-in negate function (which flips the sign of a number) to return a positive value.
Finally, we must provide the else branch. What happens if the condition is false? Because if/then/else is an expression that yields a value, the else branch is strictly mandatory. Haskell refuses to compile an if without an else because it always needs to know what value to hand back. If the number is not less than zero, we just return n.
Our function is now complete. If n is -7, the expression evaluates to 7. If n is 5, the expression evaluates to 5.
