Andr?s P?hi wrote:
What about this one?
fun mem l xs = let fun mem l (x :: xs) a = if x = l then (List.rev a) @ xs else mem l xs (x :: a) | mem l [] a = raise (Fail "Not found"); in mem' l xs [] end;
Almost, but append (@) is not tail-recursive so you need to combine List.rev and append. fun mem l xs = let fun rapp [] v = v | rapp (h::t) v = rapp t (h::v) fun mem' l (x :: xs) a = if x = l then rapp a xs else mem' l xs (x :: a) | mem' l [] a = raise (Fail "Not found"); in mem' l xs [] end;
The general point is that it's possible to avoid recursion by keeping the information elsewhere, in this case in the list. Generally, though, it's going to be faster to use the stack rather than build a list.
David