我正在尝试构建一个出现列表最小值的索引列表。
let rec max_index l =
let rec helper inList min builtList index =
match inList with
| [] -> builtList
| x :: xs ->
if (x < min) then
helper xs x index :: builtList index + 1 //line 63
else
helper xs min builtList index + 1
in helper l 100000 [] 0;;
第 63 行出现以下错误。
Error: This expression has type 'a list -> 'a list
but an expression was expected of type 'a
The type variable 'a occurs inside 'a list -> 'a list
表达式应该是 'a?我不确定它为什么这么说。我猜它与 index::builtList
最佳答案
helper xs x index :: builtList index + 1 //line 63
else
helper xs x index min index + 1
您遇到的问题是您在尝试传递 int 列表
到第 63 行的相同参数。尝试将 min
替换为 [min]
或 min::[]
。
编辑:
更新后,问题在于函数调用具有关联性并且优先级高于二元运算符(参见 here ),因此 helper xs x index
将在 index::之前执行builtList
和 helper xs x index::builtList
将在 index + 1
之前执行。要获得正确的评估顺序,您需要在其他函数调用周围加上括号,即 ::
和 +
加上它们的参数,如下所示:
helper xs x (index :: builtList) (index + 1) //line 63
else
helper xs x index min (index + 1)
关于ocaml - OCaml 中的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21819076/