这是我的代码:
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 列表中
但是如果我用 [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