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
[Caml-list] generic programming
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-07-05 (09:25)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] Re: generic programming
> On Fri, Jul 05, 2002 at 01:18:17AM +1000, John Max Skaller wrote:
> > 
> > Only two data structures in Ocaml readily admit iterators: lists and arrays.
> > Other data structures like hastables, sets, maps, etc, have control
> > inverted iterators, which are much weaker (that is, you have to provide
> > a callback which is given each value in turn

I guessed this is what John had in mind :-)

Actually, if you're desperate, you can derive a C++-style iterator
from a higher-order functional iterator (of the kind provided by the
OCaml standard library) by "inverting the control", using threads or
call/cc.  See example below.

Of course, I'm not advocating that anyone should use this trick in actual
programs.  Like François, I find functional iterators so much cleaner
and better structured.  Moreover, the extra "power" of imperative iterators
isn't obvious to me.  For instance, one could argue that imperative
iterators allow iterating in parallel over several data structures.
This is true, but how useful is iterating over two hashtables in
parallel, knowing that you will *not* scan matching keys at the same time?

- Xavier Leroy

exception End_of_iteration

let hashtbl_enumerator (h, chan) =
    (fun key data -> Event.sync (Event.send chan (Some(key, data))))
  Event.sync (Event.send chan None)

class ['a,'b] hashtbl_iterator (h : ('a, 'b) Hashtbl.t) =
      val chan = Event.new_channel ()
      initializer (ignore (Thread.create hashtbl_enumerator (h, chan)))
      method next_element =
        match Event.sync (Event.receive chan) with
          None -> raise End_of_iteration
        | Some e -> e

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