6

I've wrote the following function to find a given item "x" in a given list "lst" and return its index if it's found, otherwise it would return an error:

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

The function is fully working, I'm just wondering what is the memory consumption of it? Meaning does the memory consumption depend on the length of the list? or is it O(1)?

If it's not O(1) can someone please let me know what should I do to make it so?

Thank you

Kyle
  • 154
  • 1
  • 2
  • 13
  • 1
    By the way, OCaml has the exception constructor `Not_found` just for this kind of thing. – gsg Jul 08 '15 at 13:23

1 Answers1

5

Your function consumes constant (O(1)) space, because it's tail recursive.

You can read about tail recursion at OCaml.org, here.

Update

Here is a non-tail-recursive solution:

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

(I just noticed that PatJ already explained this, sorry :-)

Often the non-tail-recursive solution is more concise and elegant. It's too bad, but that's the way the world is sometimes.

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
  • 1
    Thank you :) Just out of curiosity, what would a function that does the same job as one I wrote, yet consumes O(n) space look like? There's no need to answer that but I'd actually like to know, since I can't think of a way to do that even after reading the link you sent me – Kyle Jul 07 '15 at 22:40
  • 2
    If the recursive call to the function wasn't the "last action" done before returning, then it would be O(n). For instance, if instead of having a counter variable `c` you would have `if (hd=x) then 0 else 1+(find x tl)` then each recursive call would add some variables to the stack. – PatJ Jul 07 '15 at 22:50
  • Thank you both! It's funny because last night I probably wrote the same exact function you both suggested yet somehow it just didn't work. OCamlWin is just so buggy sometimes. – Kyle Jul 08 '15 at 07:06