我想写一个模式匹配,如如下:错误:变量...必须在此|模式
match ... with
...
| Const1 (r, c) | Const2 (m, n)
-> expr
它返回一个错误:Error: Variable c must occur on both sides of this | pattern
。
我必须写expr
两次(一次为Const1
,其他时间为Const2
)?谁能帮忙?
我想写一个模式匹配,如如下:错误:变量...必须在此|模式
match ... with
...
| Const1 (r, c) | Const2 (m, n)
-> expr
它返回一个错误:Error: Variable c must occur on both sides of this | pattern
。
我必须写expr
两次(一次为Const1
,其他时间为Const2
)?谁能帮忙?
如错误消息所述,或模式(| pattern
)需要绑定到同一组变量。因此:
match ... with
...
| Const1 (m, n) | Const2 (m, n)
-> expr
或
match ... with
...
| Const1 (m, n) | Const2 (n, m)
-> expr
会工作。
当然,如果Const1
和Const2
接受相同的类型,你只能这样做。在某些情况下,你仍然这样做,如果你有相同类型构造的部分:
match ... with
...
| Const1 (m, _) | Const2 (_, m)
-> expr
的或图案的缺陷是,你不知道你是在构造函数,因此如果expr
逻辑依赖在Const1
或Const2
,你不能使用或模式了。
至于为什么这会是一个问题的例子,考虑是否expr
取决于r
或c
和你匹配的对象正好是Const2
类型会发生什么:
let c2 = Const2(1,2) in
match c2 with
...
| Const1 (r,c) | Const2 (m,n) -> r + 1
由于c2
是Const2
,r
没有定义在->
的右侧,所以OCaml不知道如何评估r+1
。编译器捕捉到这会发生,并让你改变你的代码以避免它。
我的猜测是,expr
不依赖于输入是否为Const1
型或Const2
的(否则你将不得不把这些情况下,在不同的行不同表情),所以你也许能
match ... with
...
| Const1 _ | Const2 _ -> expr
如果您需要匹配Const1
和Const2
都具有的某些字段,请参阅pad的答案。
啊,失去阅读错误信息的技巧.. – ygrek