Home > Software design >  Calculating length of the list recursively using guards throws "Non-exhaustive patterns in func
Calculating length of the list recursively using guards throws "Non-exhaustive patterns in func

Time:01-16

I'm trying to calculate the length of the list using different methods (just to get familiar with the language). The function using pattern matching works as expected, whereas the one using guards throws an error.

After some digging I noticed that something is probably wrong with this line (x : xs) == [] = res, but I can't figure out what exactly. Any help would be much appreciated!

Using pattern matching (works as expected)

myLength1 list = go list 0
  where
    go [] res = res
    go (x : xs) res = go xs (res   1)

Using guards (throws Non-exhaustive patterns in function go)

myLength2 list = go list 0
  where
    go (x : xs) res
      | (x : xs) == [] = res
      | otherwise = go xs (res   1)

CodePudding user response:

After some digging I noticed that something is probably wrong with this line (x:xs) == []

(x:xs) == [] can never succeed. With (x:xs) you construct a list that contains at least one element: x is the first element, and xs is a (possibly empty) list of remaining elements, whereas [] is an empty list.

If you thus call go [], it will fail to pattern match with (x:xs), since the data constructor of an empty list is [], whereas the data constructor of a "cons" is (:). This will thus indeed raise a non-exhaustive pattern error.

  •  Tags:  
  • Related