123456789101112131415161718192021222324252627282930313233343536373839404142434445464748open!Core_kernelopen!ImportmoduleDeferred=Deferred1moduleStream=structtype'at='anextDeferred.tand'anext='aTypes.Stream.next=|Nil|Consof'a*'atletsexp_of_tsexp_of_at=letrecloopdac:Sexp.t=matchDeferred.peekdwith|None->List(List.rev(Sexp.Atom"..."::ac))|SomeNil->List(List.revac)|Some(Cons(a,t))->loopt(sexp_of_aa::ac)inloopt[];;letnextt=tendtype'at='aTypes.Tail.t={(* [next] points at the tail of the stream *)mutablenext:'aStream.nextIvar.t}[@@derivingfields]letsexp_of_t_t:Sexp.t=Atom(ifIvar.is_emptyt.nextthen"<open tail>"else"<closed tail>");;letcreate()={next=Ivar.create()}letcollectt=Ivar.read(nextt)letis_closedt=Ivar.is_full(nextt)letfill_exntv=ifis_closedtthenraise_s[%message"stream is closed"]elseIvar.fill(nextt)v;;letclose_exnt=fill_exntNilletclose_if_opent=ifnot(is_closedt)thenIvar.fill(nextt)Nilletextendtv=letnext=Ivar.create()infill_exnt(Cons(v,Ivar.readnext));t.next<-next;;