OCaml的新功能查找列表中元素的索引

时间:2013-03-23 18:03:16

标签: list recursion indexing ocaml

我正在学习OCaml,我给自己的一个练习题是找到创建列表中元素的索引。到目前为止,我以为我有它,但我已经重写了这个代码块多年,似乎无法得到返回值不正确的原因。

let rec indexer_helper list element index pos found= 
match l with 
        []      ->  if (found = false) then
                        (-1)
                    else
                        index

    |   (h::t)  ->  if (h = e) then
                        index = pos
                        pos = pos + 1
                        indexer_helper t element index pos true
                    else
                        pos = pos + 1
                        indexer_helper t element index pos found;;

let rec indexer list element = indexer_helper list element 0 0 false;;

修改:问题已解决。问题是我在“更改”不可变变量时忘记使用let语句。

1 个答案:

答案 0 :(得分:3)

你在这里使用你的命令反应有点太多了。这些OCaml系列:

index = pos
pos = pos + 1

计算布尔值,而不是为变量赋值。您无法在OCaml中为变量赋值(如此)。变量是不可变的。在OCaml中编写这些行的惯用方法类似于:

let index' = pos in
let pos' = pos + 1 in
index_helper t element index' pos' true

这里还有其他错误,但这首先要弄清楚。