aboutsummaryrefslogtreecommitdiffstats
path: root/op.go
blob: 6ccc6a8d8f13488f691085f1096b9695093a8d96 (plain) (blame)
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
package main

import (
	"fmt"
	"math"
)

// parseOperator returns a closure that performs the specified arithmetic operation,
// or OpError if op is not a valid operator.
func parseOperator(op byte) (func(lhs float64, rhs float64) float64, error) {
	switch op {
	case '+':
		return func(lhs, rhs float64) float64 { return lhs + rhs }, nil
	case '-':
		return func(lhs, rhs float64) float64 { return lhs - rhs }, nil
	case '*':
		return func(lhs, rhs float64) float64 { return lhs * rhs }, nil
	case '/':
		return func(lhs, rhs float64) float64 {
			if rhs != 0 {
				return lhs / rhs
			}
			return lhs
		}, nil
	case '%':
		return func(lhs, rhs float64) float64 {
			if rhs != 0 {
				return float64(int64(lhs) % int64(rhs))
			}
			return lhs
		}, nil
	case '^':
		return func(lhs, rhs float64) float64 { return math.Pow(lhs, rhs) }, nil
	}
	return nil, OperatorErr{op}
}

// OperatorErr records an invalid arithmetic operator.
type OperatorErr struct {
	c byte
}

func (e OperatorErr) Error() string {
	return fmt.Sprintf("invalid operator: %c", e.c)
}