-
Notifications
You must be signed in to change notification settings - Fork 1
/
lazyList.ml
55 lines (47 loc) · 1.16 KB
/
lazyList.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(* Modul implementuje listy leniwe bez spamietywania. *)
type 'a t = Cons of 'a * (unit -> 'a t) | Nil
(* zwraca zwykla liste z n pierwszych elementow leniwej listy xs *)
let rec take n xs =
match n, xs with
| 0, _ -> []
| n, Nil -> []
| n, Cons (x, xs) ->
x :: take (n-1) (xs ())
;;
let rec iter f = function
| Cons (x, xs) ->
f x;
iter f (xs ())
| Nil -> ()
;;
let rec map f xs = match xs with
| Cons (x, xs) ->
Cons (f x, fun () -> map f (xs()) )
| Nil ->
Nil
;;
(* fkcja fn zwraca zwykle listy elementow. flatten_map aplikuje fn do
kazedgo elementu listy wejsciowej i tworzy (leniwa) liste powstala
przez splaszenie wyniku dzialania fn *)
let flatten_map fn inp =
let rec flatten_map acc inp =
match acc with
| (x :: xs) ->
Cons (x, fun () -> flatten_map xs inp)
| [] -> (
match inp with
| Cons (x, xs) -> flatten_map (fn x) (xs ())
| Nil -> Nil
)
in flatten_map [] inp
;;
let rec of_stream input =
match Stream.peek input with
| None -> Nil
| Some a ->
Stream.junk input ;
Cons (a, fun () -> of_stream input)
;;
let of_string input =
of_stream (Stream.of_string input)
;;