Search code examples
listfunctionhaskellpattern-matchingdefinition

Does the order of function definition matter in list patterns


So these function orders have different behaviour in GHCI:

safetailpatter xs = tail xs
safetailpatter [] = []
safetailpatter [] = []
safetailpatter xs = tail xs

The former generates the following warning and the following error when passing in []

ex3.hs:66:1: warning: [-Woverlapping-patterns]
    Pattern match is redundant
    In an equation for ‘safetailpatter’: safetailpatter [] = ...
*** Exception: Prelude.tail: empty list

As such does the order of definition matter and why? I don't see why the former overlaps while the latter doesn't as the same definitions are given.


Solution

  • Patterns are matched in order. But, what's going on here is that you are not actually parttern matching on safetailpatter xs.

    In regular english safetailpatter xs = tail xs means: safetailpatter on any variable is tail of that variable.

    What you want to match is: safetailpatter (x:xs) = tail (x:xs), which stands for: safetailpatter when applied on a list with at least one element, is tail of such a list

    Knowing this, In the code

    safetailpatter xs = tail xs
    safetailpatter [] = []
    

    Will check in order, and because the first equation matches any list input, you get a runtime error on []. Whereas

    safetailpatter (x:xs) = tail xs
    safetailpatter [] = []
    

    matches in order, and since [] doesn't match the first equation, It'll run the second, with no runtime error

    Edit

    As @chepner says, this is call irrefutable pattern. Meaning that pattern matching is happening but there is no chance to fail. Same as if you match against _