ocaml - OCaml 中的类型错误

标签 ocaml

我正在尝试构建一个出现列表最小值的索引列表。

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::之前执行builtListhelper 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/

相关文章:

algorithm - 使用纯功能深度优先搜索时如何防止循环

ocaml - 查找两个列表之间差异的库函数 - OCaml

Ocaml: "contains type variables that cannot be generalized"

ocaml - 了解 ocaml 中的基本闭包示例

ocaml - 带有可选和可变字段的记录

list - 在 OCaml 中编写列表追加函数

ocaml - 在 Ocaml 中缩写构造函数名称

functional-programming - OCaml 中表示图最常用的数据结构是什么?

dictionary - 查看字符串映射中是否存在键

function - 具有可变参数数量的 OCaml 函数