【问题标题】:New to OCaml finding index of element in a listOCaml 的新手在列表中查找元素的索引
【发布时间】:2013-03-13 11:37:37
【问题描述】:

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

【问题讨论】:

  • @JeffreyScofield 在现场。您也可以在if (h = e) then 行中问自己这个e 是什么。
  • 请保留原来的问题,这样答案对未来的读者有意义。告诉您问题已解决的 stackoverflow 方法是接受您所做的答案。

标签: list recursion indexing ocaml


【解决方案1】:

您在这里使用了过多的命令式反应。这些 OCaml 行:

index = pos
pos = pos + 1

正在计算布尔值,而不是为变量赋值。您不能在 OCaml 中为变量(本身)赋值。变量是不可变的。在 OCaml 中编写这些行的惯用方式是:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 2021-06-25
    • 2010-12-02
    • 2014-09-03
    • 2013-01-17
    • 2016-03-22
    • 2019-12-31
    相关资源
    最近更新 更多