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] Python's yield, Lisp's call-cc or C's setjmp/longjmp in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-12-17 (20:04)
From: David Brown <caml-list@d...>
Subject: Re: [Caml-list] Python's yield, Lisp's call-cc or C's setjmp/longjmp in OCaml
On Wed, Dec 17, 2003 at 08:14:21PM +0100, Pierre Weis wrote:
> [...]
> > This only works for simple examples. Try for example writing a
> > function which successively yields all possible moves for a chess
> > board. The "yield" operator really helps there.
> Very interesting: please give us the code corresponding to this
> example, in order for us to realize how the full power of the "yield"
> operator helps to solve this problem.

Perhaps this isn't the best example, since the problem is so large.

The icon language has been around with a similar operator for quite a
while.  It is very useful for prolog-type backtracking, since the code
can be written fairly naturally.

However, this construct is fairly easy to implement in regular OCaml.

The following works, but requires -rectypes to compile:

  open Printf
  type 'a thump = 'a * (unit -> 'a thump)
  (* Return the numbers a through b and stop. *)
  let through a b () : int thump =
    let rec loop num () =
      if num > b then raise End_of_file;
      num, loop (num + 1) in
    loop a ()
  (* Sample to show the results. *)
  let show () =
    let rec loop op =
      let num, op = op () in
      printf "%d," num;
      loop op in
    try loop (through 1 10)
    with End_of_file ->
      printf "\n"
  let () = show ()

With a bit more work, you can write it without needing the rectypes.  If
the construct is needed, perhaps it could be done in ocamlp4.  It would
probably have to rewrite the iterative constructs recursively, though.


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