more efficient Array.of_seq (only allocates one intermediate list, then reverse the array);

test of Array.to_seq and Sequence.append
This commit is contained in:
Simon Cruanes 2013-01-29 14:31:21 +01:00
parent 1e90120295
commit 087c38aa0c
3 changed files with 30 additions and 4 deletions

View file

@ -137,8 +137,16 @@ module Array =
struct
let of_seq seq =
(* intermediate list... *)
let l = List.of_seq seq in
Array.of_list l
let l = List.of_rev_seq seq in
let a = Array.of_list l in
(* reverse array *)
let n = Array.length a in
for i = 0 to (n-1) / 2 do
let tmp = a.(i) in
a.(i) <- a.(n-i-1);
a.(n-i-1) <- tmp;
done;
a
let to_seq a = from_iter (fun k -> Array.iter k a)
@ -181,6 +189,16 @@ module Hashtbl =
from_iter (fun k -> Hashtbl.iter (fun a b -> k (a, b)) h)
end
module String =
struct
let to_seq s = from_iter (fun k -> String.iter k s)
let of_seq seq =
let b = Buffer.create 64 in
iter (fun c -> Buffer.add_char b c) seq;
Buffer.contents b
end
module Int =
struct
let range ~start ~stop =
@ -197,7 +215,6 @@ module Int =
module Set(S : Set.S) =
struct
type set = S.t
type elt = S.elt
let to_seq set = from_iter (fun k -> S.iter k set)

View file

@ -137,6 +137,12 @@ module Hashtbl :
(** Sequence of key/value pairs from the hashtable *)
end
module String :
sig
val to_seq : string -> char t
val of_seq : char t -> string
end
(** Sequences of ints *)
module Int :
sig
@ -153,7 +159,6 @@ module Int :
module Set(S : Set.S) :
sig
type set = S.t
type elt = S.elt
val to_seq : set -> elt t

View file

@ -33,4 +33,8 @@ let _ =
Format.printf "l3=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l3;
Format.printf "s={@[<h>%a@]}@." (Sequence.pp_seq Format.pp_print_int) (ISetSeq.to_seq set);
Format.printf "l4=@[<h>[%a]@]@." (pp_list Format.pp_print_int) l4;
Format.printf "l3[:5]+l4=@[<h>[%a]@]@." (Sequence.pp_seq Format.pp_print_int)
(Sequence.Array.to_seq
(Sequence.Array.of_seq (Sequence.append
(Sequence.take 5 (Sequence.List.to_seq l3)) (Sequence.List.to_seq l4))));
()