I'm going through the learn you a haskell tutorial and I've been tripping over some of the examples the author has given.
For example he reimplemented zip as follows:
zip' :: [a] -> [b] -> [(a,b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys
He uses a similar approach for all his other examples, where he puts the most specific patterns first. Here is a slightly different version of the zip function:
zip' :: [a] -> [b] -> [(a,b)]
zip' (x:xs) (y:ys) = (x, y):zip' xs ys
zip' _ _ = []
As far as I understand both methods do the same thing. If an empty list is provided either way (x:xs) or (y:ys) won't match which will finish the recursion by appending the empty list [].
- I personally prefer the second version for readability, but maybe I'm wrong in doing so.
- Does it have any effect on the performance of a method? As far as I understand if the top most pattern does not match, Haskell will check against the next pattern. Does the order of the patterns affect performance?
Kind regards,
Edit:
Possibly duplicate of: Haskell GHC: what is the time complexity of a pattern match with N constructors?
Summary: The order of the patterns is very important for the semantics (in terms of strict evaluation of the arguments) and the readability of a function. The pattern match itself will always be in O(1) time complexity.