2021-02-14 02:09:56 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
2021-02-20 20:52:27 +00:00
|
|
|
// ErrEmpty denotes an empty stack
|
|
|
|
var ErrEmpty = fmt.Errorf("stack empty")
|
|
|
|
|
|
|
|
// ErrUnderflow denotes a PICK that tried to pick a value that didn't exist
|
|
|
|
var ErrUnderflow = fmt.Errorf("cannot pick value from beyond stack depth")
|
|
|
|
|
2021-02-14 02:09:56 +00:00
|
|
|
// Stack is a stack of integers with no defined max depth
|
|
|
|
type Stack struct {
|
|
|
|
values []int
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pop returns the top of the stack
|
|
|
|
func (s *Stack) Pop() (int, error) {
|
|
|
|
if len(s.values) == 0 {
|
2021-02-20 20:52:27 +00:00
|
|
|
return 0, ErrEmpty
|
2021-02-14 02:09:56 +00:00
|
|
|
}
|
|
|
|
i := s.values[0]
|
|
|
|
s.values = s.values[1:]
|
|
|
|
return i, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Push adds a value to the top of the stack
|
|
|
|
func (s *Stack) Push(i int) {
|
|
|
|
s.values = append([]int{i}, s.values...)
|
|
|
|
}
|
2021-02-15 01:32:38 +00:00
|
|
|
|
|
|
|
// Pick grabs a value from the given depth in the stack, non-destructively.
|
|
|
|
func (s *Stack) Pick(i int) (int, error) {
|
2021-02-20 20:52:27 +00:00
|
|
|
if len(s.values) <= i {
|
|
|
|
return 0, ErrUnderflow
|
2021-02-15 01:32:38 +00:00
|
|
|
}
|
|
|
|
return s.values[i], nil
|
|
|
|
}
|