我写了下面这个函数,用于在给定的列表 "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
这个函数完全可以工作,我只是想知道它的内存消耗是多少?也就是说,内存消耗是否取决于列表的长度?还是O(1)?
如果不是O(1),请问有人能告诉我该怎么做才能使其达到O(1)吗?
谢谢。
Not_found
。 - gsg