Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Variable ... must occur on both sides of this | pattern

I want to write a pattern matching like the follows:

match ... with
...
| Const1 (r, c) | Const2 (m, n) 
  -> expr

It returns an error: Error: Variable c must occur on both sides of this | pattern.

Do I have to write expr twice (one time for Const1, the other time for Const2)? Could anyone help?

like image 612
SoftTimur Avatar asked Nov 28 '25 00:11

SoftTimur


1 Answers

As the error message said, Or pattern (| pattern) requires binding to the same set of variables. Therefore:

match ... with
...
| Const1 (m, n) | Const2 (m, n) 
  -> expr

or

match ... with
...
| Const1 (m, n) | Const2 (n, m) 
  -> expr

would work.

Of course, you only can do that if Const1 and Const2 accept the same type. In some cases, you still do so if you have parts of constructs with the same type:

match ... with
...
| Const1 (m, _) | Const2 (_, m) 
  -> expr

The pitfall of Or pattern is that you don't know which constructor you are in. So if logic of expr depends on Const1 or Const2, you couldn't use Or pattern anymore.

like image 146
pad Avatar answered Dec 02 '25 05:12

pad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!