Sof*_*mur 2 ocaml pattern-matching
我想写一个匹配如下的模式:
match ... with
...
| Const1 (r, c) | Const2 (m, n)
-> expr
Run Code Online (Sandbox Code Playgroud)
它返回一个错误:Error: Variable c must occur on both sides of this | pattern.
我必须写expr两次(一次是Const1,另一次是Const2)?有人可以帮忙吗?
正如错误消息所述,或者pattern(| pattern)需要绑定到同一组变量.因此:
match ... with
...
| Const1 (m, n) | Const2 (m, n)
-> expr
Run Code Online (Sandbox Code Playgroud)
要么
match ... with
...
| Const1 (m, n) | Const2 (n, m)
-> expr
Run Code Online (Sandbox Code Playgroud)
会工作.
当然,如果Const1并且Const2接受相同类型,您只能这样做.在某些情况下,如果你有一些具有相同类型的构造,你仍然会这样做:
match ... with
...
| Const1 (m, _) | Const2 (_, m)
-> expr
Run Code Online (Sandbox Code Playgroud)
Or模式的缺陷是你不知道你在哪个构造函数.所以如果逻辑expr依赖于Const1或者Const2,你就不能再使用Or模式了.