Version française
Home     About     Download     Resources     Contact us    
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: -- (:)
From: brogoff@s...
Subject: Re: [Caml-list] Python's yield, Lisp's call-cc or C's setjmp/longjmp in OCaml
On 17 Dec 2003, Falk Hueffner wrote:
> ijtrotts@ucdavis.edu writes:
>
> > Why not do this:
> >
> > # let rec number() =
> >    let i=ref(-1) in fun() ->
> >     incr i;
> >     !i, if !i mod 2 = 0 then "Even" else "Odd";;
> > val number : unit -> unit -> int * string = <fun>
> > # let n=number();;
> > val n : unit -> int * string = <fun>
> > # Array.init 10 (fun _ -> n());;
> > - : (int * string) array =
> > [|(0, "Even"); (1, "Odd"); (2, "Even"); (3, "Odd"); (4, "Even"); (5, "Odd");
> >   (6, "Even"); (7, "Odd"); (8, "Even"); (9, "Odd")|]
>
> 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.

While I think yield is pretty cool, having used in Sather, which got in from CLU
I believe,you can simulate this control flow and more using higher order
functions. Sticking with the simple example, but ditching the array and rolling
my own streams with core ML yields (ha!)

type  'a generator = Nil | Cons of 'a * (unit -> 'a generator);;

let rec odd_even i j =
  if i > j then
    Nil
  else
    Cons(i, (fun () -> odd_even (succ i) j));;

let rec print_upto n = function
    Nil -> ()
  | Cons(i, f) ->
      if i <= n then
	let s = if i mod 2 = 0 then "EVEN" else "ODD" in
        (Printf.printf "(%i, %s)\n" i s;
          print_upto n (f()))
      else
        ();;

which has similar semantics to the Python yield, except that the generator is
not consumed during the traversal. It should be obvious how to encode that
behavior by modifying print_upto to return the remaining generator.

In any case, programming this kind of thing in ML is pretty easy, so I don't
think we need an extension to the language for yield. callcc is more powerful,
but I don't like the possibility that making callcc fast penalizes code which
doesn't use it. We have exceptions and threads already.

-- Brian


-------------------
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