-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmean.go
More file actions
37 lines (31 loc) · 750 Bytes
/
mean.go
File metadata and controls
37 lines (31 loc) · 750 Bytes
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
package arithmetic
import (
"errors"
"fmt"
)
func init() {
RegisterFunction("mean", mean)
}
// mean is a function that returns the mean of the provided inputs.
func mean(args ...interface{}) (interface{}, error) {
if len(args) == 0 {
return nil, errors.New("mean requires at least one argument")
}
// Ensure each argument is a float, or a "variable" float.
var sum float64
for _, a := range args {
switch t := a.(type) {
case float64:
sum += t
case variable:
v, ok := t.value.(float64)
if !ok {
return nil, fmt.Errorf("mean requires numeric arguments, %s given", t)
}
sum += v
default:
return nil, fmt.Errorf("mean requires numeric arguments, %v given", a)
}
}
return sum / float64(len(args)), nil
}