-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpqueue_list.sml
58 lines (51 loc) · 1.42 KB
/
pqueue_list.sml
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
structure Pqueue =
struct
(* REPRESENTATION CONVENTION:
A list of elements with key d and data d
REPRESENTATION INVARIANT:
- the key of each element is less or
equal to the key of the next one
- the data of each element must be unique
*)
type ''a queue = (int * ''a) list
(* empty
TYPE: queue
PRE: (none)
POST: an empty queue
*)
val empty = []
(* isEmpty T
TYPE: queue -> bool
PRE: (none)
POST: true if and only if the queue is empty
*)
fun isEmpty [] = true
| isEmpty _ = false
(* insert (Q, k, d )
TYPE: queue * int * ''a -> queue
PRE: (none)
POST: Q with element of k and d
*)
fun insert ([], k, d) = [(k, d)]
| insert ( (x as (k1,d1))::xs, k, d) = if k <= k1 then (k, d)::(x::xs) else x::insert(xs, k, d)
(* extractMin Q
TYPE: queue -> (int,''a) * queue
PRE: Q is not empty
POST: ((k,d), Q’), where k is the minimum key of Q and d is the data of that element,
and H’ is H without that element
*)
fun extractMin queue = (hd queue, tl queue)
(* remove (Q, d )
TYPE: queue * ''a -> queue
PRE: (none)
POST: Q without element with d
*)
fun remove( [], d ) = []
| remove( (x as (_,d1))::xs, d) = if d1 = d then xs else x::remove(xs,d)
(* update( Q, k, d )
TYPE: queue * int * ''a -> queue
PRE: (none)
POST: Q with updated key to k for element which has data = d
*)
fun update( queue, k, d ) = insert( remove( queue, d ), k, d )
end