The if expression allows you to perform different actions based on one or more conditions. In the example below, we calculate the price of a product. If the customer buys at least 5 units of our product, we grant him a discount. Price refers to a component named price and amount to the component named amount.
if Amount >= 5 then Price * 0.9 else Price end
To break this down: Writing an if expression follows these rules:
- Every if expression begins with the keyword if and an arbitrary logic expression: the condition.
- If the condition is true, the expression that follows the then keyword will be executed.
- If the condition is false, the expression that follows the else keyword will be executed instead.
- Every if expression ends with the keyword end. This is to distinguish the else expression from any subsequent ones. We will see why this is necessary in the next example.
You can also define more than one condition in an if expression. Let's look at a more complex example. Imagine we wanted to give customers an additional discount if they buy more than 9 units, and let's also add some shipping costs to the price:
if Amount > 9 then Price * 0.8 elif Amount >= 5 then Price * 0.9 else Price end + ShippingCosts
Let's break it down again:
- We first check if the amount is greater than 9. We must check for this first because only one condition in an if can be true, and conditions are looked at one after another. If the greater-than-5 condition would come first, any number greater than 9 would also satisfy it and we'd never reach the next condition.
- Subsequent conditions start with the elif keyword (that's a combination of else and if). Aside from the queer name, it's basically the same as the initial if.
- You can use as many elif expressions as you like, but there can only be one if and one else expression.
- Every if expression results in a value that can be processed further. In this case, we add the ShippingCosts to whatever price was calculated by the if.
- This is also the reason why every if must have an else expression: without it, there is no guarantee that the if would return a value. In our example, an amount of 3 would satisfy neither of our two conditions.