forked from clipperhouse/slice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaverage.go
47 lines (43 loc) · 1.33 KB
/
average.go
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
package slice
import "github.com/clipperhouse/typewriter"
var average = &typewriter.Template{
Name: "Average",
Text: `
// Average sums {{.SliceName}} over all elements and divides by len({{.SliceName}}). See: http://clipperhouse.github.io/gen/#Average
func (rcv {{.SliceName}}) Average() ({{.Type}}, error) {
var result {{.Type}}
l := len(rcv)
if l == 0 {
return result, errors.New("cannot determine Average of zero-length {{.SliceName}}")
}
for _, v := range rcv {
result += v
}
result = result / {{.Type}}(l)
return result, nil
}
`,
TypeConstraint: typewriter.Constraint{Numeric: true},
}
var averageT = &typewriter.Template{
Name: "Average",
Text: `
// Average{{.TypeParameter.LongName}} sums {{.TypeParameter}} over all elements and divides by len({{.SliceName}}). See: http://clipperhouse.github.io/gen/#Average
func (rcv {{.SliceName}}) Average{{.TypeParameter.LongName}}(fn func({{.Type}}) {{.TypeParameter}}) (result {{.TypeParameter}}, err error) {
l := len(rcv)
if l == 0 {
err = errors.New("cannot determine Average[{{.TypeParameter}}] of zero-length {{.SliceName}}")
return
}
for _, v := range rcv {
result += fn(v)
}
result = result / {{.TypeParameter}}(l)
return
}
`,
TypeParameterConstraints: []typewriter.Constraint{
// exactly one type parameter is required, and it must be numeric
{Numeric: true},
},
}