Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml: Bad style, all clauses in this pattern-matching are guarded

I get a "Error: Warning 25: bad style, all clauses in this pattern-matching are guarded"

What does "guarded" mean?

My code has pattern matching-

match z with
    | y when List.length z = 0 -> ...
    | y when List.length z > 0 -> ...
like image 988
Aspen Avatar asked Dec 15 '11 04:12

Aspen


1 Answers

The guards are the when parts. What the compiler is telling you is that it can't tell whether your match is exhaustive (covers all possible cases), but that it might not be. The compiler can't really tell for sure, because exhaustiveness is undecidable for arbitrary expressions. The compiler just figures you should have at least one pattern without a guard because when the match is exhaustive, a guard on the last case would be redundant.

Since you know your match is exhaustive, the compiler is basically right. Your second guard is redundant. You can just leave it off with no difference in meaning:

match z with
| y when List.length z = 0 -> ...
| y -> ...

This will make the compiler happy.

I like this warning; it has found a few logic errors for me over the years.

If this code isn't just an example but is really what you wrote, it would be much more idiomatic to write it like this:

match z with
| [] -> ...
| head :: tail -> ...

It's also a tiny bit more efficient since it won't bother to calculate the length of the list and then discard the result.

If you don't need to destructure the list, you can make it simpler still:

if z = [] then
    ...
else
    ...
like image 137
Jeffrey Scofield Avatar answered Sep 24 '22 05:09

Jeffrey Scofield