From 546a77ba8fa470920139bd1a6a51521d50a9e00c Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Mon, 28 Jan 2013 00:09:48 +0100 Subject: [PATCH] modules to convert lists and hashtables from/to sequences --- sequence.ml | 17 +++++++++++++++++ sequence.mli | 14 ++++++++++++++ tests.ml | 18 ++++-------------- 3 files changed, 35 insertions(+), 14 deletions(-) diff --git a/sequence.ml b/sequence.ml index 738fc28..0fbed29 100644 --- a/sequence.ml +++ b/sequence.ml @@ -49,3 +49,20 @@ let drop n seq = let seq_fun k = seq.seq_fun (fun x -> if !count >= n then k x else incr count) in { seq_fun; } + +module List = + struct + let of_seq seq = List.rev (fold (fun y x -> x::y) [] seq) + let to_seq l = from_iter (fun k -> List.iter k l) + end + +module Hashtbl = + struct + let of_seq seq = + let h = Hashtbl.create 3 in + iter (fun (k,v) -> Hashtbl.replace h k v) seq; + h + let to_seq h = + from_iter (fun k -> Hashtbl.iter (fun a b -> k (a, b)) h) + end + diff --git a/sequence.mli b/sequence.mli index b613f7c..ecfeaba 100644 --- a/sequence.mli +++ b/sequence.mli @@ -31,3 +31,17 @@ val take : int -> 'a sequence -> 'a sequence val drop : int -> 'a sequence -> 'a sequence (** Drop the [n] first elements of the sequence *) + +(** {2 Basic data structures converters} *) + +module List : + sig + val of_seq : 'a sequence -> 'a list + val to_seq : 'a list -> 'a sequence + end + +module Hashtbl : + sig + val of_seq : ('a * 'b) sequence -> ('a, 'b) Hashtbl.t + val to_seq : ('a, 'b) Hashtbl.t -> ('a * 'b) sequence + end diff --git a/tests.ml b/tests.ml index 206ac87..53f93ae 100644 --- a/tests.ml +++ b/tests.ml @@ -1,18 +1,6 @@ (** {2 Test sequences} *) -let seq_of_list l = Sequence.from_iter (fun k -> List.iter k l) - -let list_of_seq seq = List.rev (Sequence.fold (fun y x -> x::y) [] seq) - -let seq_of_hashtbl h = - Sequence.from_iter (fun k -> Hashtbl.iter (fun a b -> k (a, b)) h) - -let hashtbl_from_seq seq = - let h = Hashtbl.create 3 in - Sequence.iter (fun (k,v) -> Hashtbl.replace h k v) seq; - h - (** print a list of items using the printing function *) let rec pp_list ?(sep=", ") pp_item formatter = function | x::y::xs -> Format.fprintf formatter "%a%s@,%a" @@ -22,8 +10,10 @@ let rec pp_list ?(sep=", ") pp_item formatter = function let _ = let l = [0;1;2;3;4;5;6] in - let l' = list_of_seq (Sequence.filter (fun x -> x mod 2 = 0) (seq_of_list l)) in - let l'' = list_of_seq (Sequence.take 3 (Sequence.drop 1 (seq_of_list l))) in + let l' = Sequence.List.of_seq + (Sequence.filter (fun x -> x mod 2 = 0) (Sequence.List.to_seq l)) in + let l'' = Sequence.List.of_seq + (Sequence.take 3 (Sequence.drop 1 (Sequence.List.to_seq l))) in Format.printf "l=@[[%a]@]@." (pp_list Format.pp_print_int) l; Format.printf "l'=@[[%a]@]@." (pp_list Format.pp_print_int) l'; Format.printf "l''=@[[%a]@]@." (pp_list Format.pp_print_int) l'';