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

问题描述 投票:-5回答:1

我正在学习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语句。

list recursion indexing ocaml
1个回答
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

这里还有其他错误,但这让我觉得首先要弄明白。

© www.soinside.com 2019 - 2024. All rights reserved.