English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

Browse thread
tail rec
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-05-21 (12:57)
From: Brian Hurt <bhurt@j...>
Subject: Re: [Caml-list] tail rec
skaller wrote:

>I have a silly idea. Introduce a new construction:
>let tailrec f .. 
>This is the same as let rec except it checks every direct call to f
>is in tail position (and bombs out the compiler if not).
I dislike this idea, even for it's stated purpose (to make it easier for 
people to learn Ocaml).  Wether a particular call is a tail call or not 
is not an attribute of the function, but an attribute of the call.  The 
same function can be called as both a tail call and a non-tail call.  If 
we're going to teach Ocaml, let's at least teach it right.

And this is a non-trivial complaint.  It's very common for me to write 
recursive loops where the call inside the function is a tail call, but 
the original call to the function is not a tail call.  So I couldn't write:
    let tailrec loop i s =
        if i > 0 then
            loop (i-1) (s+i)  (* proper tail call- it's a loop *)
        else s
    let t = 2 * (loop n 0) in ... (* this is not a tail call *)

A better proposal would be one where the call itself is marked as a 
tailcall, and bombs out if that call isn't.  Maybe something like:

    let rec loop i s =
       if i > 0 then
          tailcall loop (i-1) (s+i) (* force this to be a tailcall *)
       else s
    let t = 2 * (loop n 0) in ... (* not a tail call, and that's OK *)

At which point I'm neutral on the idea.  The rules for what is or isn't 
a tail call are not complicated.  On the other hand, it's a little bit 
of extra correctness for not much cost.