Search code examples
pattern-matchingocaml

Non-exhaustive pattern matching issue


I made a dummy function that takes in a list of two lists, as shown below:

# let rec test ([a;b]) = match [a;b] with
    [] -> []
  | h::t -> 
          if ((List.length h) > 0) then
              [List.hd a]
          else
              []
;;

And I get this warning in return:

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]

But in the function above, am I matching for [] in the first match of the match function?

The warning makes sense, because when I execute test([]);;, I get an error. I'm just not sure who to check for this case when I thought I was already doing it with the code above.


Solution

  • Your patterns in the match expression are exhaustive, in fact they're more than exhaustive since the pattern [] will never be able to match the expression [a;b].

    What isn't exhaustive is your pattern in the function signature (([a;b])). You should replace that pattern with a plain parameter name and then match on that. So your could would look like this:

    let rec test xs = match xs with
      ...
    

    or alternatively you could just use function and not name the parameter at all:

    let rec test = function
      ...