Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading