在列表中查找项目并返回其索引-OCaml

Kyl*_*yle 5 ocaml list ml find memory-consumption

我编写了以下函数,以在给定列表“ lst”中找到给定项“ x”,并在找到后返回其索引,否则将返回错误:

exception Failure of string

let rec func x lst c = match lst with
    | [] -> raise(Failure "Not Found")
    | hd::tl -> if (hd=x) then c else func x tl (c+1)


let find x lst = func x lst 0
Run Code Online (Sandbox Code Playgroud)

该功能可以正常使用,我只是想知道它的内存消耗是多少?这意味着内存消耗是否取决于列表的长度?还是O(1)?

如果不是O(1),有人可以让我知道该怎么做吗?

谢谢

Jef*_*eld 5

您的函数消耗恒定 (O(1)) 空间,因为它是尾递归的。

您可以在 OCaml.org 的此处阅读有关尾递归的信息。

更新

这是一个非尾递归的解决方案:

exception Failure of string

let rec find x lst =
    match lst with
    | [] -> raise (Failure "Not Found")
    | h :: t -> if x = h then 0 else 1 + find x t
Run Code Online (Sandbox Code Playgroud)

(我刚刚注意到 PatJ 已经解释了这一点,抱歉:-)

通常非尾递归解决方案更加简洁和优雅。这太糟糕了,但世界有时就是这样。

  • 如果对函数的递归调用不是返回之前完成的“最后一个操作”,那么它将是 O(n)。例如,如果不是使用计数器变量“c”,而是使用“if (hd=x) then 0 else 1+(find x tl)”,那么每个递归调用都会向堆栈添加一些变量。 (2认同)