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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
package main
import (
"fmt"
"math"
"strconv"
"strings"
)
type Stack []float64
func (s *Stack) push(v float64) {
*s = append(*s, v)
}
func (s *Stack) pop() *float64 {
if len(*s) > 0 {
v := (*s)[len(*s)-1]
*s = (*s)[:len(*s)-1]
return &v
}
return nil
}
type Calculator struct {
stack Stack
buf string
}
// swap swaps the values of the buffer and the bottom element of the stack. If
// the buffer is empty this simply pops from the stack. If the stack is empty,
// this simply pushes to the stack.
func (c *Calculator) swap() {
st := c.stack.pop()
if con := parseConstant(c.buf); con != nil {
c.stack.push(*con)
} else if f, err := strconv.ParseFloat(c.buf, 64); err == nil {
c.stack.push(f)
}
if st != nil {
c.buf = strings.TrimSpace(printStackVal(*st))
} else {
c.buf = ""
}
}
// performOp performs the specified arithmetic operation and returns nil or
// OpError if op is not a valid operator.
func (c *Calculator) performOp(op byte) error {
if len(c.stack) < 1 {
return nil
}
fn, err := parseOp(op)
if err != nil {
return err
}
if con := parseConstant(c.buf); con != nil {
fn(&c.stack[len(c.stack)-1], *con)
} else if fl, err := strconv.ParseFloat(c.buf, 64); err == nil {
fn(&c.stack[len(c.stack)-1], fl)
} else if len(c.stack) > 1 {
fn(&c.stack[len(c.stack)-2], c.stack[len(c.stack)-1])
c.stack = c.stack[:len(c.stack)-1]
}
c.buf = ""
return nil
}
// parseOp returns a closure that performs the specified arithmetic operation,
// or OpError if op is not a valid operator.
func parseOp(op byte) (func(lhs *float64, rhs float64), error) {
switch op {
case '+':
return func(lhs *float64, rhs float64) { *lhs += rhs }, nil
case '-':
return func(lhs *float64, rhs float64) { *lhs -= rhs }, nil
case '*':
return func(lhs *float64, rhs float64) { *lhs *= rhs }, nil
case '/':
return func(lhs *float64, rhs float64) {
if rhs != 0 {
*lhs /= rhs
}
}, nil
case '%':
return func(lhs *float64, rhs float64) {
if rhs != 0 {
*lhs = float64(int64(*lhs) % int64(rhs))
}
}, nil
case '^':
return func(lhs *float64, rhs float64) { *lhs = math.Pow(*lhs, rhs) }, nil
}
return nil, OpError{op}
}
// OpError records an invalid arithmetic operator.
type OpError struct {
c byte
}
func (e OpError) Error() string {
return fmt.Sprintf("invalid operator: %c", e.c)
}
|