OCaml中的类型错误
我试图建立一个索引列表,其中列表的最小值出现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 help
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;;
表达式应为“a”类型?我不知道它为什么这么说。我猜这与index::builtList
helper xs x index :: builtList index + 1 //line 63
else
helper xs x index min index + 1
您遇到的问题是,您试图将非列表传递给第65行(min
)上的helper函数,同时尝试将int list
传递给第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)
你需要一些括号。函数调用绑定比二进制运算符更紧密。所以
if (x < min) then
helper xs x (index :: builtList) (index + 1)
else
helper xs min builtList (index + 1)
如果(x
事实上,我把这两行错抄了。我已经更新了。同样的错误我希望你能帮我。。你知道如何使它更安全/多态吗?现在,当我运行它时,我得到了这个表达式的float类型,但是一个表达式应该是int
-line类型62@user2079802如果(x,那么?我想这是在比较int和float。我唯一能猜到的是你的参数l
中有浮点数。
if (x < min) then
helper xs x (index :: builtList) (index + 1)
else
helper xs min builtList (index + 1)