-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbst_topk.if
More file actions
43 lines (38 loc) · 864 Bytes
/
bst_topk.if
File metadata and controls
43 lines (38 loc) · 864 Bytes
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
data Tree = Empty | Node { value, left, right };
extern fn append(a, b) explain { Concatenates two lists. };
extern fn take_k(xs, k) explain { Returns first k items from list. };
fn insert(t, x) =
match t {
Empty => Node { value: x, left: Empty, right: Empty };
Node { value, left, right } =>
if x < value {
Node {
value,
left: insert(left, x),
right
}
} else {
Node {
value,
left,
right: insert(right, x)
}
};
};
fn to_desc_list(t) =
match t {
Empty => [];
Node { value, left, right } => append(to_desc_list(right), append([value], to_desc_list(left)));
};
fn topk(t, k) =
t
|> to_desc_list
|> take_k(k);
Empty
|> insert(5)
|> insert(2)
|> insert(8)
|> insert(1)
|> insert(3)
|> insert(7)
|> topk(3)