-
Notifications
You must be signed in to change notification settings - Fork 12
/
mathable.go
51 lines (41 loc) · 1.1 KB
/
mathable.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
48
49
50
51
package fuego
// MathableStream is a Stream of Mathable type.
type MathableStream[T Mathable] struct {
Stream[T]
}
// Sum return the sum of all items on the stream.
// Panics if the channel is nil or the stream is empty.
// This is a special case of a reduction.
// This is a terminal operation and hence expects the producer to close the stream in order to complete.
func (s MathableStream[T]) Sum() T {
if s.stream == nil {
panic(PanicMissingChannel)
}
sum, ok := <-s.stream
if !ok {
panic(PanicNoSuchElement)
}
for val := range s.stream {
sum = Sum(sum, val)
}
return sum
}
// Average returns the arithmetic average of the numbers in the stream.
// Panics if the channel is nil or the stream is empty.
// This is a special case of a reduction.
// This is a terminal operation and hence expects the producer to close the stream in order to complete.
func (s MathableStream[T]) Average() T {
if s.stream == nil {
panic(PanicMissingChannel)
}
sum, ok := <-s.stream
if !ok {
panic(PanicNoSuchElement)
}
var cnt T = 1
for val := range s.stream {
sum += val
cnt++
}
return sum / cnt
}