Version franēaise
Home     About     Download     Resources     Contact us    
Browse thread
Locally-polymorphic exceptions [was: folding over a file]
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: kirillkh <kirillkh@g...>
Subject: Re: [Caml-list] Re: Locally-polymorphic exceptions [was: folding over a file]
Hi,

2007/10/3, Daniel de Rauglaudre <daniel.de_rauglaudre@inria.fr>:
>
> Hi,
>
> > 2007/10/3, oleg@pobox.com <oleg@pobox.com>:
> >
> > exception Done of 'a
> >
> >  let fold_file (file: in_channel)
> >               (read_func: in_channel->'a)
> >               (elem_func: 'a->'b->'b)
> >               (seed: 'b) =
> > [...]
>
> Personnally, I don't like exceptions because they generally control too
> much part of code.


It's easy enough to localize the exception scope in this case and to see
that catching it at the top recursive invocation gets rid of it for sure.
Even the most dreadful beast is harmless, when encapsulated in a cage. (C)

I wonder what are continuations' maintenance properties, though. Any
comments? I'm not fluent in them, yet.

I often practice things like:
>
>   match try Some (...) with [ Exception -> None ] with
>   [ Some v -> blabla
>   | None -> blublu ]
>
> I would write your function like this:
>
>   value fold_file (file : in_channel) (read_func : in_channel -> 'a)
>     (elem_func : 'a -> 'b -> 'b) (seed : 'b)
>   =
>     let rec loop prev_val =
>       match try Some (read_func file) with [ End_of_file -> None ] with
>       [ Some input ->
>           let combined_val = elem_func input prev_val in
>           loop combined_val
>       | None -> prev_val ]
>     in
>     loop seed
>   ;


A similar solution has been proposed in the original discussion ("best and
fastest way to read lines from a file?" thread). But then someone suggested
using a second exception instead, which is better performance-wise, since it
avoids variant allocations on the common code path. What I tried to do with
polymorphic exception is implement a generalized channel fold combinator
based on this idea.

-Kirill