aboutsummaryrefslogtreecommitdiffstats
path: root/op.go
blob: ab57a84a478e00cdcd5a08832a60a92b3b89b4e7 (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
package main

import (
	"fmt"
	"math"
)

// 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)
}