stack.go
1109 bytes
1package rpn
2
3import (
4 "fmt"
5)
6
7var ErrNotEnoughValuesTmpl = "Need at least %d values on the stack to perform this operation"
8
9type Stack struct {
10 values []float64
11}
12
13func (s *Stack) Push(value float64) {
14 s.values = append(s.values, value)
15}
16
17func (s *Stack) Pop() (float64, error) {
18 count := s.Len()
19 if count == 0 {
20 return 0, fmt.Errorf(ErrNotEnoughValuesTmpl, 1)
21 }
22 value := s.values[count-1]
23 s.values = s.values[:count-1]
24 return value, nil
25}
26
27func (s *Stack) Pop2() (float64, float64, error) {
28 count := s.Len()
29 if count < 2 {
30 return 0, 0, fmt.Errorf(ErrNotEnoughValuesTmpl, 2)
31 }
32 a := s.values[count-1]
33 b := s.values[count-2]
34 s.values = s.values[:count-2]
35 return a, b, nil
36}
37
38func (s *Stack) Len() int {
39 return len(s.values)
40}
41
42func (s *Stack) Swap() error {
43 count := s.Len()
44 if count < 2 {
45 return fmt.Errorf(ErrNotEnoughValuesTmpl, 2)
46 }
47 a := s.values[count-1]
48 b := s.values[count-2]
49 s.values[count-1] = b
50 s.values[count-2] = a
51 return nil
52}
53
54func (s *Stack) Clear() {
55 s.values = []float64{}
56}
57
58func (s *Stack) Values() []float64 {
59 return append([]float64(nil), s.values...)
60}