我想寫一個模式匹配,如如下:錯誤:變量...必須在此|模式
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