Version française
Home     About     Download     Resources     Contact us    
Browse thread
try and tail call
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Chris King <colanderman@g...>
Subject: Re: [Caml-list] try and tail call
On 10/21/06, Christophe Raffalli <raffalli@univ-savoie.fr> wrote:
>
> consider this piece of code:
>
>   (try
>     let b = f a in
>     (fun () -> g b)
>   with
>     (fun () -> h a)) ()
>
>
> Is the call to "g" a tail call and is it omptimized as such ?

Yes, it is, at least in the assembly code output by ocamlopt.  (Neat
trick, btw.)

> If not, how to encode a feature like this one:
>
>   try
>     ...
>   end
>     ... (* the exception raised here are not handles by with but
> propagated *)
>   with
>     ...

What's typically used is something along the lines of:

match (try Some (f a) with Not_found -> None) with
| Some b -> g b
| None -> h a

though I wouldn't be surprised if the method you used above is
slightly faster since it avoids creating unnecessary option objects
(the anonymous functions are statically allocated).

> By the way I think this "try ... [end ...] with ..." syntax is usefull
> anyway because you have often a bug when
> you write
>
> try
>   let b = f a in (* you know this may raise Not_found *)
>   g b (* you assume wrongly that this can not raise Not_found *)
> with
>   Not_found -> h a
>
> The unwanted capture of Not_found could be avoided with try ... end ...
> with ...

Many people agree with you... I find almost always that I want
something like the syntax you describe above, rather than what Caml
provides natively.  Martin Jambon provides an example syntax extension
in his Camlp4 tutorial[1] which allows the use of "let-try-in-with"
blocks:

let b = try f a in g b
with Not_found -> h a

Here, only exceptions raised by "f a" are caught by the try block, and
"g b" occurs in a recursive context.

Hope this helps,
Chris

[1] http://martin.jambon.free.fr/extend-ocaml-syntax.html#lettry