conversion with Gen

This commit is contained in:
Simon Cruanes 2014-04-16 17:57:11 +02:00
parent 93b6a18c41
commit 281032c61f
2 changed files with 31 additions and 4 deletions

View file

@ -210,7 +210,7 @@ module MList = struct
let to_seq l k = iter k l let to_seq l k = iter k l
let to_stream l = let _to_next arg l =
let cur = ref l in let cur = ref l in
let i = ref 0 in (* offset in cons *) let i = ref 0 in (* offset in cons *)
let rec get_next _ = match !cur with let rec get_next _ = match !cur with
@ -218,13 +218,17 @@ module MList = struct
| Cons (_, n, tl) when !i = !n -> | Cons (_, n, tl) when !i = !n ->
cur := !tl; cur := !tl;
i := 0; i := 0;
get_next 42 (* any value would do *) get_next arg
| Cons (a, n, _) -> | Cons (a, n, _) ->
let x = a.(!i) in let x = a.(!i) in
incr i; incr i;
Some x Some x
in in get_next
Stream.from get_next
let to_gen l = _to_next () l
let to_stream l =
Stream.from (_to_next 42 l) (* 42=magic cookiiiiiie *)
end end
(** Iterate on the sequence, storing elements in a data structure. (** Iterate on the sequence, storing elements in a data structure.
@ -554,6 +558,21 @@ let to_set (type s) (type v) m seq =
(fun set x -> S.add x set) (fun set x -> S.add x set)
S.empty seq S.empty seq
type 'a gen = unit -> 'a option
let of_gen g =
(* consume the generator to build a MList *)
let rec iter1 k = match g () with
| None -> ()
| Some x -> k x; iter1 k
in
let l = MList.of_seq iter1 in
MList.to_seq l
let to_gen seq =
let l = MList.of_seq seq in
MList.to_gen l
(** {2 Functorial conversions between sets and sequences} *) (** {2 Functorial conversions between sets and sequences} *)
module Set = struct module Set = struct

View file

@ -329,6 +329,14 @@ val of_set : (module Set.S with type elt = 'a and type t = 'b) -> 'b -> 'a t
val to_set : (module Set.S with type elt = 'a and type t = 'b) -> 'a t -> 'b val to_set : (module Set.S with type elt = 'a and type t = 'b) -> 'a t -> 'b
(** Convert the sequence to a set, given the proper set module *) (** Convert the sequence to a set, given the proper set module *)
type 'a gen = unit -> 'a option
val of_gen : 'a gen -> 'a t
(** Traverse eagerly the generator and build a sequence from it *)
val to_gen : 'a t -> 'a gen
(** Make the sequence persistent (O(n)) and then iterate on it. Eager. *)
(** {2 Functorial conversions between sets and sequences} *) (** {2 Functorial conversions between sets and sequences} *)
module Set : sig module Set : sig