I need to detect a commutative pattern in one of my functions. I thought that writing the following will do the work:
let my_fun a b = match a,b with
(*...*)
| a,b
| b,a when is_valid b -> process b (***)
(*...*)
This doesn't work and Ocaml complains with this sub-pattern is unused
warning for the line marked with (***)
.
1) Can someone explain to me what this warning try to say and why this doesn't work?
2) How can I actually write this elegantly without using if then else
given the fact that I want to now which argument is_valid
?
2) Is it possible to get the intended functionality using only pattern matching and without repeating when is_valid b -> process b
as it happens bellow?
let my_fun a b = match a,b with
(*...*)
| a,b when is_valid b -> process b
| b,a when is_valid b -> process b
(*...*)
Edit:
In my concrete example a
and b
are pairs. The function is a bit more complicated but the following will illustrate the case:
let f a b = match a,b with
| (a1,a2),(b1,b2)
| (b1,b2),(a1,a2) when b1 = b2 -> a1 + a2
Calling f (1,1) (1,2)
will yield pattern match failed. I know understand why (thanks to the answers bellow) and I understand how I can make it work if I have different constructors for each element (as in Ashish Agarwal's answer). Can you suggest a way to make it work in my case?