fork download
  1. type 'a list_t =
  2. | Nil
  3. | Cons of 'a * 'a node
  4. and 'a node = 'a list_t Lazy.t
  5.  
  6. let rec lazy_map fn xs = lazy (
  7. match Lazy.force xs with
  8. | Nil -> Nil
  9. | Cons(x, rest) -> Cons (fn x, lazy_map fn rest)
  10. )
  11.  
  12. let rec lazy_take n xs = lazy (
  13. match (n, Lazy.force xs) with
  14. | (0, _) -> Nil
  15. | (_, Nil) -> Nil
  16. | (n, Cons(a, rest)) -> Cons(a, lazy_take (n-1) rest)
  17. )
  18.  
  19. let rec lazy_repeated x = lazy (
  20. Cons(x, lazy_repeated x)
  21. )
  22.  
  23. let rec to_list xs =
  24. match Lazy.force xs with
  25. | Nil -> []
  26. | Cons(a, rest) -> a::to_list rest
  27.  
  28. let rec lazy_merge xs ys =
  29. match (Lazy.force xs, Lazy.force ys) with
  30. | (_, Nil) -> xs
  31. | (Nil, _) -> ys
  32. | (Cons(x, xs'), Cons(y, ys')) ->
  33. if x = y then lazy (Cons(x, lazy_merge xs' ys'))
  34. else if x < y then lazy (Cons(x, lazy_merge xs' ys))
  35. else lazy (Cons(y, lazy_merge xs ys'))
  36.  
  37. let rec lazy_iter fn xs =
  38. match Lazy.force xs with
  39. | Nil -> ()
  40. | Cons(x, rest) -> fn x; lazy_iter fn rest
  41.  
  42.  
  43. let _ =
  44. let rec h = lazy (Cons(1, lazy_merge (lazy_map (( * ) 2) h) (lazy_map (( * ) 3) h))) in
  45. lazy_iter (fun x -> ignore x) (lazy_take 10 h)
  46.  
Runtime error #stdin #stdout 0.01s 2780KB
stdin
Standard input is empty
stdout
Standard output is empty