我正在尝试建立列表最小值出现的索引列表。
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
答案 0 :(得分:5)
helper xs x index :: builtList index + 1 //line 63
else
helper xs x index min index + 1
您遇到的问题是,您尝试将第0行(min
)上的非列表传递给辅助函数,同时尝试将int list
传递给相同的参数第63行。尝试将min
替换为[min]
或min::[]
。
编辑:
更新之后,问题是函数调用是左关联的并且优先于二元运算符(请参阅here),因此helper xs x index
将在index :: builtList
之前执行,同样{{1将在helper xs x index :: builtList
之前执行。要获得正确的评估顺序,您需要将括号括在其他函数调用周围,即index + 1
和::
加上他们的参数,如下所示:
+
答案 1 :(得分:3)
你需要一些括号。函数调用比二元运算符更紧密。所以
if (x < min) then
helper xs x (index :: builtList) (index + 1)
else
helper xs min builtList (index + 1)