Syntactic Sugar I: if and case
Let's learn a few common syntactic variants for conditions and reusable subexpressions.
We'll cover the following
In the next two lessons, we explore a few more syntax features of Haskell. These features can be considered syntactic sugar – they do not allow us to express anything we could not do with our current repertoire of syntax constructs. However, they allow the expression of certain functions in a more readable way. Most of them make use of Haskell’s layout syntax, i.e., they span several lines and need to be indented appropriately. We start with some variants of conditional expressions and matching.
If-expressions
If-expressions are conditional expressions that have a syntax similar to if-statements in other programming languages. The difference is that they are not statements, but expressions.
An if-expression has the form
if condition then expression_1 else expression_2
where the condition is an expression of type Bool
, and the other two expressions can have any type, but they must both have the same one.
If the condition evaluates to True
, then the result of the if-expression is the value of expression_1
, otherwise the result is the value of expression_2
.
Let’s reconsider the sign
function from our previous lesson on guarded equations. It was defined like this:
sign :: Int -> Int
sign n | n > 0 = 1
| n < 0 = -1
| n == 0 = 0
Using two nested if-expressions, we can rewrite it as:
sign :: Int -> Int
sign n = if n > 0 then 1 else if n < 0 then -1 else 0
We have moved the conditional logic from the guards to the right side of the equation, which also allows us to define the function in just one equation. That’s not very readable though. We can improve it a bit by splitting it up into several lines.
Get hands-on with 1200+ tech skills courses.