1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950openInternalopenStreamexceptionZarErrorofstringletpositive_of_int(i:int):positive=ifi<1thenraise(ZarError("positive_of_int: int must be positive, got "^string_of_inti))elseletrecgo(j:int):positive=ifj==1thenXHelseifjmod2==0thenXO(go@@j/2)elseXI(go@@j/2)ingoiletrecint_of_positive=function|XH->1|XOp'->2*int_of_positivep'|XIp'->2*int_of_positivep'+1letz_of_int(i:int):z=ifi==0thenZ0elseifi>0thenZpos(positive_of_inti)elseZneg(positive_of_int(-i))letint_of_z=function|Z0->0|Zposp->int_of_positivep|Znegp->-int_of_positivepletqmakend={qnum=z_of_intn;qden=positive_of_intd}(** Run an itree sampler to produce a single sample from a given
stream of bits. Returns the unconsumed rest of the stream. *)letrecruntbs=matchobservetwith|RetFx->x,bs|TauFt'->runt'bs|VisF(_,k)->run(k(Obj.magic(firstbs)))(restbs)letrecrun_forevertbs=letx,bs'=runtbsinSCons(x,fun_->run_forevertbs')