This repository was archived by the owner on Nov 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathstack.mini
More file actions
82 lines (71 loc) · 1.85 KB
/
stack.mini
File metadata and controls
82 lines (71 loc) · 1.85 KB
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
//
// Copyright 2020, Offchain Labs, Inc. All rights reserved.
//
type Stack = option<StackCell>;
type StackCell = struct {
top: [8]any,
num: uint,
rest: option<StackCell>
};
public func stack_new() -> Stack {
None
}
public func stack_push(stack: Stack, value: any) -> Stack {
if let Some(cell) = unsafecast<option<StackCell> >(stack) {
if cell.num < 8 {
return Some(
cell with {
top: cell.top with { [cell.num] = value }
} with {
num: 1 + cell.num
}
);
}
}
Some(struct {
top: newfixedarray(8) with { [0] = value },
num: 1,
rest: stack
})
}
public func stack_isEmpty(stack: Stack) -> bool {
stack == None<StackCell>
}
public func stack_pop(stack: Stack) -> option<(Stack, any)> {
let cell = stack?;
if cell.num == 1 {
Some((unsafecast<Stack>(cell.rest), cell.top[0]))
} else {
Some((
Some(cell with { num: cell.num - 1 }),
cell.top[cell.num-1]
))
}
}
public func stack_size(stack: Stack) -> uint {
let size = 0;
loop {
if let Some(res) = stack_pop(stack) {
stack = res.0;
size = size+1;
} else {
return size;
}
}
}
public throw func stack_discardDeepestItems(stack: Stack, numToDiscard: uint) -> Stack {
stack_ddi2(stack, numToDiscard).0
}
throw func stack_ddi2(stack: Stack, numToDiscard: uint) -> (Stack, uint) {
if let Some(res) = stack_pop(stack) {
let (ustack, val) = res;
let (subStack, subNum) = stack_ddi2(ustack, numToDiscard);
if subNum == 0 {
(stack_push(subStack, val), 0)
} else {
(subStack, subNum-1)
}
} else {
(stack, numToDiscard) // stack is empty
}
}