I am very new to Haskell and to functional programming in general. My question is pretty basic. What is the difference between Pattern Matching and Guards?
Funct
To me it looks like Pattern Matching and Guards are fundamentally the same. Both evaluate a condition, and if true will execute the expression hooked to it. Am I correct in my understanding?
Not quite. First pattern matching can not evaluate arbitrary conditions. It can only check whether a value was created using a given constructor.
Second pattern matching can bind variables. So while the pattern []
might be equivalent to the guard null lst
(not using length because that'd not be equivalent - more on that later), the pattern x:xs
most certainly is not equivalent to the guard not (null lst)
because the pattern binds the variables x
and xs
, which the guard does not.
A note on using length
: Using length
to check whether a list is empty is very bad practice, because, to calculate the length it needs to go through the whole list, which will take O(n)
time, while just checking whether the list is empty takes O(1)
time with null
or pattern matching. Further using `length´ just plain does not work on infinite lists.