问题描述
这是我的代码:
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出现在'列表中
但是,如果我将 h1 :: res 替换为 [h1] @res ,则该代码有效,但我没有得到此问题的确切原因,请提供帮助。
注意:-成员是一个自定义函数,如果元素属于列表l2则返回true,否则返回false。
解决方法
您的问题是intersection t1 l2 h1::res
中的优先事项。 OCaml尝试评估intersection t1 l2 h1
,然后将其限制为{'1}列表类型的res
。您需要手动指定运算符优先级。你可以做
intersection t1 l2 (h1::res)
或者,您可以使用application operator from the Pervasives module。如文档中所述,g @@ f @@ x
与g (f (x))
intersection t1 l2 @@ h1::res