Ocaml: Bad style, all offers in this pattern matching are protected

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

What does β€œprotected” mean?

My code has pattern matching -

 match z with | y when List.length z = 0 -> ... | y when List.length z > 0 -> ... 
+7
source share
1 answer

Guards are parts of when . The compiler tells you that it cannot determine if your match is exhaustive (covers all possible cases), but it may not be. The compiler cannot say for sure, because comprehensive information is insoluble for arbitrary expressions. The compiler simply indicates that you should have at least one template without a protector, because when the match is exhaustive, protection in the latter case will be redundant.

Since you know that your match is exhaustive, the compiler is basically right. Your second guard is redundant. You can simply leave it without a difference in meaning:

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

This will make the compiler happy.

I like this warning; he found several logical errors for me over the years.

If this code is not only an example, but also what you wrote, it would be much more idiomatic to write it as follows:

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

It is also slightly more efficient, as it will not want to calculate the length of the list and then discard the result.

If you don't need to destroy the list, you can make it even easier:

 if z = [] then ... else ... 
+16
source

All Articles