[英]OCaml list issue with cons operator
這是我的代碼:
let rec intersection l1 l2 res =
match l1 with
| [] -> res
| h1 :: t1 ->
(
match l2 with
| [] -> []
| h2 :: t2 ->
if member h1 l2 = true then
intersection t1 l2 h1::res
else
intersection t1 l2 res
)
問題在於h1::res部分,它會引發以下錯誤:
錯誤:此表達式的類型為“a 列表,但預期的表達式為“a 類型”類型變量“a”出現在“a 列表”內
但是,如果我用[h1]@res替換h1::res則代碼有效,我沒有得到這個問題的確切原因,請幫忙。
注意: member 是一個自定義函數,如果元素屬於列表 l2,則返回 true,否則返回 false。
您的問題是intersection t1 l2 h1::res
的優先級。 OCaml 正在嘗試評估intersection t1 l2 h1
,然后將其計算為res
,它是一個列表類型。 您需要手動指定運算符優先級。 你可以這樣做
intersection t1 l2 (h1::res)
或者,您可以使用Pervasives 模塊中的 應用程序運算符。 如文檔中所述, g @@ f @@ x
與g (f (x))
intersection t1 l2 @@ h1::res
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.