mirror of
https://github.com/c-cube/iter.git
synced 2025-12-06 03:05:29 -05:00
Sequence.to_stream implemented (O(n) memory and time)
This commit is contained in:
parent
d7ce7eb30e
commit
836049b6f1
3 changed files with 22 additions and 2 deletions
13
sequence.ml
13
sequence.ml
|
|
@ -317,11 +317,22 @@ let array_slice a i j =
|
|||
k a.(idx); (* iterate on sub-array *)
|
||||
done
|
||||
|
||||
(** Sequence of elements of a stream *)
|
||||
(** Sequence of elements of a stream (usable only once) *)
|
||||
let of_stream s =
|
||||
let seq k = Stream.iter k s in
|
||||
from_iter seq
|
||||
|
||||
(** Convert to a stream. The sequence is made persistent. *)
|
||||
let to_stream seq =
|
||||
let l = ref (MList.of_seq seq) in
|
||||
let i = ref 0 in
|
||||
let rec get_next () =
|
||||
if !l == MList._empty () then None
|
||||
else if (!l).MList.len = !i then (l := (!l).MList.tl; i := 0; get_next ())
|
||||
else let x = (!l).MList.content.(!i) in (incr i; Some x)
|
||||
in
|
||||
Stream.from (fun _ -> get_next ())
|
||||
|
||||
(** Push elements of the sequence on the stack *)
|
||||
let to_stack s seq = iter (fun x -> Stack.push x s) seq
|
||||
|
||||
|
|
|
|||
|
|
@ -158,7 +158,10 @@ val array_slice : 'a array -> int -> int -> 'a t
|
|||
from [i] to [j] *)
|
||||
|
||||
val of_stream : 'a Stream.t -> 'a t
|
||||
(** Sequence of elements of a stream *)
|
||||
(** Sequence of elements of a stream (usable only once) *)
|
||||
|
||||
val to_stream : 'a t -> 'a Stream.t
|
||||
(** Convert to a stream. linear in memory and time (a copy is made in memory) *)
|
||||
|
||||
val to_stack : 'a Stack.t -> 'a t -> unit
|
||||
(** Push elements of the sequence on the stack *)
|
||||
|
|
|
|||
6
tests.ml
6
tests.ml
|
|
@ -94,6 +94,12 @@ let _ =
|
|||
(Sequence.of_array
|
||||
(Sequence.to_array (Sequence.append
|
||||
(Sequence.take 5 (Sequence.of_list l3)) (Sequence.of_list l4))));
|
||||
(* sequence, persistent, etc *)
|
||||
let seq = Sequence.int_range ~start:0 ~stop:100000 in
|
||||
let seq' = Sequence.persistent seq in
|
||||
let stream = Sequence.to_stream seq' in
|
||||
Format.printf "test length [0..100000]: persistent1 %d, stream %d, persistent2 %d"
|
||||
(Sequence.length seq') (Sequence.length (Sequence.of_stream stream)) (Sequence.length seq');
|
||||
(* maps *)
|
||||
Format.printf "@[<h>map: %a@]@."
|
||||
(Sequence.pp_seq (fun formatter (k,v) -> Format.fprintf formatter "\"%s\" -> %d" k v))
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue