forked from tianyicui/pfds-ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch4.ml
52 lines (46 loc) · 1.1 KB
/
ch4.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
module type STREAM =
sig
type 'a stream_cell =
| Nil
| Cons of 'a * 'a stream
and 'a stream =
'a stream_cell Lazy.t
val (++) : 'a stream -> 'a stream -> 'a stream
val take : int -> 'a stream -> 'a stream
val drop : int -> 'a stream -> 'a stream
val reverse : 'a stream -> 'a stream
end
module Stream : STREAM =
struct
type 'a stream_cell =
| Nil
| Cons of 'a * 'a stream
and 'a stream =
'a stream_cell Lazy.t
let rec (++) xs ys = lazy (
match xs with
| lazy Nil -> Lazy.force ys
| lazy (Cons (x, s)) -> Cons (x, s ++ ys)
)
let rec take n l = lazy (
match n, l with
| 0, _
| _, lazy Nil -> Nil
| _, lazy (Cons (x, s)) ->
Cons (x, take (n-1) s)
)
let drop n s = lazy (
let rec drop' = function
| (0, s) -> Lazy.force s
| (n, lazy Nil) -> Nil
| (n, lazy (Cons (x, s))) -> drop' (n-1, s)
in drop' (n, s)
)
let reverse s = lazy (
let rec reverse' l acc =
match Lazy.force l with
| Nil -> acc
| Cons (x, s) -> reverse' s (Cons (x, lazy acc))
in reverse' s Nil
)
end