Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 2.07 KB | None | 0 0
  1. type 'a stream=Cons of 'a*(unit->'a stream);;
  2. type history={reference:int list;iter:int};;
  3.  
  4. (*convert n element of stream to a list*)
  5. let rec to_list n (Cons(v,f))=match n with
  6.     |0->[]
  7.     |_->[v]@(to_list (n-1) (f ()));;
  8.  
  9. (*check for existence of value v in list l*)
  10. let rec exists v l=match l with
  11.     |[]->false
  12.     |x::xs->if v==x then true else exists v (List.tl l);;
  13.  
  14. (*remove duplicates from list*)
  15. let unique l=
  16.     let rec temp uniq orig=match orig with
  17.     |[]->uniq
  18.     |x::xs->if exists x uniq then temp uniq xs else temp (uniq@[x]) xs in
  19.     temp [] l;;
  20.  
  21. (*traverse the first n streams and listify the first m elements (from m=n to 1)
  22. this serves as a way to traverse the stream of streams without getting stuck in one stream forever*)
  23. let rec list_of_streams n (Cons(s,f))=match n with
  24.     |1->(to_list 1 s)
  25.     |_->(to_list n s)@(list_of_streams (n-1) (f ()));;
  26.  
  27. (*take 2 lists and return a list with elements that appear in source list but not in reference list
  28. this serves as a way of finding new elements that haven't been put in the flattened stream yet*)
  29. let cut_overlap src refer=
  30.     let rec temp res s r=match s with
  31.         |[]->res
  32.         |x::xs->if exists x r
  33.         then temp res (List.tl s) r
  34.         else temp (res@[(List.hd s)]) (List.tl s) r in
  35.     temp [] src refer;;
  36.  
  37. (*considering which elements have been put in the flattened stream already (hist), find next eligible element in stream of streams*)
  38. let rec next_uniq hist (Cons(s,f))=
  39.     let curr=cut_overlap (unique (list_of_streams hist.iter (Cons(s,f)))) hist.reference in
  40.     match (List.length curr) with
  41.         |0->next_uniq {reference=hist.reference;iter=(hist.iter+1)} (Cons(s,f))
  42.         |_->{reference=(List.hd curr)::hist.reference;iter=hist.iter};;
  43.  
  44. (*take stream of streams and return flattened stream - only unique elements from stream of streams appear in it*)
  45. (*the issue is that line 4 wants to have (Cons(int,fun ()->stream)) but gets (Cons(fun history->int,fun ()->stream))*)
  46. let flatten (Cons(s,f))=
  47.     let rec temp n hist=
  48.         let h=next_uniq hist (Cons(s,f)) in
  49.         (Cons((List.hd h.reference),(fun ()->temp h))) in
  50.     temp {reference=[];iter=1};;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement