aboutsummaryrefslogtreecommitdiffstats
path: root/op.go
blob: 3a193b6e634ea42c2615c8afb169265eaaeeb973 (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
46
47
48
package main

import (
	"fmt"
	"math"
)

// Op is a binary operator.
type Op func(lhs, rhs float64) float64

// parseOp parses a binary operator, returning a function that performs the operation, or
// OpError if op is not a valid operator.
func parseOperator(op byte) (Op, 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)
}