Skip to content

Instantly share code, notes, and snippets.

@mariusae
Created September 13, 2010 07:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mariusae/576922 to your computer and use it in GitHub Desktop.
Save mariusae/576922 to your computer and use it in GitHub Desktop.
python generators in ocaml using delimcc
type ('a, 'b) t = Done | More of 'a * ('b -> ('a, 'b) t)
let gen f =
(*
* Note: the first value to yield gets thrown away as the generator
* has not yet started.
*)
let start _ =
let p = Delimcc.new_prompt () in
Delimcc.push_prompt p begin fun () ->
f (fun x -> Delimcc.shift0 p (fun k -> More (x, k))); Done
end in
let next = ref start in
fun rv ->
match !next rv with
| More (x, k) -> next := k; Some x
| Done -> None
(* ==EXAMPLE USE== *)
open Printf
let rec take_all t count =
match t count with
| Some i -> printf "took: %d\n" i; take_all t (count + 1)
| None -> ()
let () =
let take = gen begin fun yield ->
for i = 0 to 10 do
let rv = yield i in
printf "got: %d\n" rv
done
end in
take_all take 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment