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

Finding an item in a list and returning its index - OCaml

我编写了以下函数来查找给定列表 "lst" 中的给定项目 "x" 和 return 如果找到它的索引,否则它会 return 一个错误:

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

功能完全正常,我只是想知道它的内存消耗是多少?意思是内存消耗取决于列表的长度吗?还是 O(1)?

如果不是 O(1),有人可以告诉我我应该怎么做才能做到这一点吗?

谢谢

你的函数消耗常量 (O(1)) space,因为它是尾递归的。

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

更新

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

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

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

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