Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] copying Streams
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Pierre.Boulet@l...
Subject: Re: [Caml-list] copying Streams
> Is there any way to copy a Stream (from the standard library)
> in such a way that the original stream is not modified when the
> copy is used and vice versa?

I have not managed yet to do what you want but I may have a
workaround: here is a function that builds two streams from another
one such that the two produced streams work together to only remove
elements form the source stream when both have read it. They thus
appear as two independent streams containing the same elements.

let stream_get_nth n s =
  let i = (n+1)-(Stream.count s) in
    try List.nth (Stream.npeek i s) (i-1)
    with Failure "nth" -> raise Stream.Failure

let stream_duplicate s =
  let start_count = Stream.count s in
  let count1 = ref start_count 
  and count2 = ref start_count in
  let get c1 c2 n =
    let n' = n + start_count in
      if n' < !c1 then raise Stream.Failure
      else begin
	incr c1;
	if n' >= !c2
	  try Some (stream_get_nth n' s)
	  with Stream.Failure -> None
	  try Some ( s)
	  with Stream.Failure -> None
    end in
  let get1 n = get count1 count2 n
  and get2 n = get count2 count1 n
    (Stream.from get1), (Stream.from get2)

-- -

     In theory, practice and theory are the same, 
     but in practice they are different. -- Larry McVoy
Bug reports:  FAQ:
To unsubscribe, mail  Archives: