我正在尝试构建列表最小值出现的索引列表.
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;;
Run Code Online (Sandbox Code Playgroud)
第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
Run Code Online (Sandbox Code Playgroud)
表达式是'a?' 我不确定为什么这么说.我猜这与它有关index::builtList
helper xs x index :: builtList index + 1 //line 63
else
helper xs x index min index + 1
Run Code Online (Sandbox Code Playgroud)
您遇到的问题是,您尝试将第63 行(min
)上的非列表传递给辅助函数,同时尝试将int list
第63行传递给第63行的相同参数.请尝试min
使用[min]
或替换min::[]
.
编辑:
在更新之后,问题在于函数调用是左关联的并且优先于二元运算符(参见此处),因此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)
Run Code Online (Sandbox Code Playgroud)