2011-11-27 46 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的答案。