OCaml中的类型错误

3
我正在尝试构建一个列表,其中包含列表最小值出现的索引。
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有关。

2个回答

5
        helper xs x index :: builtList index + 1 //line 63
    else
        helper xs x index min index + 1

你遇到的问题是在第65行(min)尝试将非列表传递给你的帮助函数,而在第63行尝试将int list传递给同一参数。尝试用[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)

我实际上把那两行代码复制错了,我已经更新了。但是错误还是一样的。 - Collin
还有一件事,我希望你能帮忙... 你知道如何使它更加类型安全/多态吗?现在当我运行它时,我得到了 This expression has type float but an expression was expected of type int - line 62。 - Collin
@user2079802,你是从 if (x < min) then 得到的吗? - N_A
我认为它的意思是你正在将一个整数与一个浮点数进行比较。我唯一能猜测的是你的参数“l”中包含浮点数。 - N_A

3
你需要加上一些括号。函数调用的优先级比二元操作符高。所以:
if (x < min) then
    helper xs x (index :: builtList) (index + 1)
else
    helper xs min builtList (index + 1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接