2011-11-27 126 views
2

我想写一个模式匹配,如如下:错误:变量...必须在此|模式

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

它返回一个错误:Error: Variable c must occur on both sides of this | pattern

我必须写expr两次(一次为Const1,其他时间为Const2)?谁能帮忙?

+0

啊,失去阅读错误信息的技巧.. – ygrek

回答

5

如错误消息所述,或模式(| pattern)需要绑定到同一组变量。因此:

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

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

会工作。

当然,如果Const1Const2接受相同的类型,你只能这样做。在某些情况下,你仍然这样做,如果你有相同类型构造的部分:

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

的或图案的缺陷是,你不知道你是在构造函数,因此如果expr逻辑依赖在Const1Const2,你不能使用或模式了。

0

至于为什么这会是一个问题的例子,考虑是否expr取决于rc和你匹配的对象正好是Const2类型会发生什么:

let c2 = Const2(1,2) in 
match c2 with 
... 
| Const1 (r,c) | Const2 (m,n) -> r + 1 

由于c2Const2r没有定义在->的右侧,所以OCaml不知道如何评估r+1。编译器捕捉到这会发生,并让你改变你的代码以避免它。

我的猜测是,expr不依赖于输入是否为Const1型或Const2的(否则你将不得不把这些情况下,在不同的行不同表情),所以你也许能

脱身
match ... with 
... 
| Const1 _ | Const2 _ -> expr 

如果您需要匹配Const1Const2都具有的某些字段,请参阅pad的答案。

相关问题