haskell function / pattern operator

A friend of mine showed me the following code:

calculateAge :: (Int, Int, Int) -> Int
calculateAge (d2, m2, y2)
   | 11 > m2 = 2021 - y2
   | 11 == m2 && 10 >= d2 = 2021 - y2
   | otherwise = 2021 - y2 - 1

What does the | operator stand for? Is it just if the pattern are matching that the rest will get executed? Or is it like a Constructor?

>Solution :

| is not an operator. It is a guard [wiki]. The expression after the | is a boolean expression. If it evaluates to True, then it will "fire" the expression that is associated with it.

This thus means that if the pattern matches, the guards will be evaluated top to bottom, and for the first guard that evaluates to True, it will fire the corresponding expression. otherwise is just an alias for True, so otherwise will always evaluate to True. This means that if no guard listed before the otherwise guard fires, the clause with otherwise will fire.

Leave a Reply