What is pattern matching in Haskell and how is it related to guarded equations?
I’ve tried looking for a simple explanation, but I haven’t found one.
EDIT:
Someone tagged as homework. I don’t go to school anymore, I’m just learning Haskell and I’m trying to understand this concept. Pure out of interest.
In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.
Compare:
with the equivalent Haskell:
Note the “n ≥ 2″ in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as
x:xs,(x, y, z), orJust x. In a piecewise definition, conditions based on=or∈relations (basically, the conditions that say something “is” something else) become patterns. Guards allow for more general conditions. We could rewritefibto use guards: