Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] looping recursion
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Prevost <j.prevost@g...>
Subject: Re: [Caml-list] looping recursion
Oops.  Hit the send button before I meant to...

Anyway, that little loop with Boom example should show why the try
prevents the inner call from being in tail position: because the try
block's expressions can refer to variables in the scope of the
original function call, there's a possible continuation (you raise an
exception) that brings those variables back into scope.

The compiler *could*, I suppose, do some magic and notice when there
are no locally bound variables in the exception code path, but even
just thinking about how that might be implemented, I think it could
get messy.  What if it's not always the same try block that's around
the call that would otherwise be a tail call?  What if the fact that
there are multiple exception handlers is important, like:

exception Boom2 of int

let rec loop2 x =
  try
    if x < 100 then loop2 (x + x) else raise (Boom2 0)
  with Boom2 y -> raise (Boom2 (y + 1))

let use_loop2 x = try loop2 x with Boom2 y -> y

In this second example, use_loop2 is using the exceptions in loop2 to
calculate the result.  (Admittedly, this is a bizarre little setup.)

So figuring out if it's "safe" to make it a tail call is hard--not to
mention it would probably end up confusing the user even more if it
did work only part of the time.  (How do I change this so it's
recongnized as tail recursive again?)

Hope this helps.  :)  I tried to find an FAQ entry on this, because I
thought there was one, but was unable to find anything.

John.

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners