-
Notifications
You must be signed in to change notification settings - Fork 1
/
stack.ml
82 lines (63 loc) · 1.85 KB
/
stack.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
exception Empty
exception Subscript
module type STACK =
sig
type 'a stack
val empty : 'a stack
val isEmpty : 'a stack -> bool
val cons : 'a -> 'a stack -> 'a stack
val head : 'a stack -> 'a (* raises Empty if stack is empty *)
val tail : 'a stack -> 'a stack (* raises Empty if stack is empty *)
val update : 'a stack -> int -> 'a -> 'a stack
val (++) : 'a stack -> 'a stack -> 'a stack
end
module List : STACK =
struct
type 'a stack = 'a list
let empty = []
let isEmpty xs = xs = []
let cons x xs = x::xs
let head = function
| [] -> raise Empty
| hd::_ -> hd
let tail = function
| [] -> raise Empty
| _::tl -> tl
let rec (++) xs ys =
match xs with
| [] -> ys
| hd::tl -> hd::(tl ++ ys)
let rec update xs i v =
match xs, i with
| [], _ -> raise Subscript
| _::tl, 0 -> v::tl
| hd::tl, i -> hd :: update tl (i-1) v
end
module CustomStack : STACK =
struct
type 'a stack = Nil | Cons of 'a * 'a stack
let empty = Nil
let isEmpty = function
| Nil -> true
| _ -> false
let cons hd tl = Cons (hd, tl)
let head = function
| Nil -> raise Empty
| Cons(hd, _) -> hd
let tail = function
| Nil -> raise Empty
| Cons(_, tl) -> tl
let rec update xs i v =
match xs, i with
| Nil, _ -> raise Subscript
| Cons (_, tl), 0 -> cons v tl
| Cons (hd, tl), i -> cons hd (update tl (i-1) v)
let rec (++) xs ys =
match xs with
| Nil -> ys
| Cons (hd, tl) -> cons hd (tl ++ ys)
end
(* Exercise 2.1 *)
let rec suffixes xs =
if List.isEmpty xs then List.empty
else List.cons (List.head xs) (suffixes (List.tail xs))