Browse thread
[Caml-list] Python's yield, Lisp's call-cc or C's setjmp/longjmp in OCaml
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: | 2003-12-17 (06:29) |
From: | ijtrotts@u... |
Subject: | Re: [Caml-list] Python's yield, Lisp's call-cc or C's setjmp/longjmp in OCaml |
On Tuesday 16 December 2003 10:10, Dustin Sallings wrote: > On Dec 16, 2003, at 10:42, Brian Hurt wrote: > > By my measurements, Ocaml's exceptions are faster than C's > > setjmp/longjmp. > > Ocaml doesn't provide first-class continuations, but most of the things > > people actually do with call-cc can be done in other ways in Ocaml. I > > don't know what Python's yield instruction does. > > Simple example: > > from __future__ import generators > > def number(max): > for i in range(max): > if(i % 2 == 0): > yield i, "Even" > else: > yield i, "Odd" > > for n in number(10): > print n > > The output of this example is as follows: > > (0, 'Even') > (1, 'Odd') > (2, 'Even') > (3, 'Odd') > (4, 'Even') > (5, 'Odd') > (6, 'Even') > (7, 'Odd') > (8, 'Even') > (9, 'Odd') > > It's basically a special case of an upward continuation (or is it > downward? I'm bad with terminology). I think you can get pretty close > to this behavior with streams, but it's still not as easy as a return > statement that has a resume type thing. 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")|] ? Issac ------------------- 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