Function signature
func Reduce(fn interface{}) outputArguments
| Name | Type | Description |
|---|---|---|
| fn | func | This function must receive two arguments, the first argument is an accumulator and the second a element of the same type that the elements in the stream. The output of this function will have the same type than the accumulator |
Output
| Name | Type | Description |
|---|---|---|
| output | stream.output | It returns the output (value and error) |
Errors
| Type | Message |
|---|---|
| err.items-nil | A nil stream can not be reduced |
| err.invalid-argument | The reduce operation requires a function as argument |
| err.invalid-argument | The provided function must retrieve 2 arguments |
| err.invalid-argument | The provided function must return 1 value |
| err.invalid-argument | The type of the second argument in the provided function must be %s |
| err.invalid-argument | The type of the first argument and the output in the provided function must be the same |
Examples
package main
import (
"fmt"
"github.com/wesovilabs/koazee"
)
var numbers = []int{1, 3, 5, 7, 9}
func main() {
avg := koazee.Stream().
With(numbers).
Reduce(func(acc, item int) int {
return acc + item
}).Int()
fmt.Printf("The average is %d\n", avg)
}package main
import (
"fmt"
"github.com/wesovilabs/koazee"
)
type genre int
const (
female genre = iota
male
)
type primate struct {
name string
age int
family string
genre genre
}
func newPrimate(name string, age int, family string, genre genre) *primate {
return &primate{
name: name,
age: age,
family: family,
genre: genre,
}
}
var primates = []*primate{
newPrimate("John", 15, "Capuchin", male),
newPrimate("Laura", 12, "Squirrel monkey", female),
newPrimate("Benjamin", 23, "Spider monkey", male),
newPrimate("George", 19, "Golden Lion Tamarin", male),
newPrimate("Jane", 33, "Orangutan", female),
newPrimate("Sarah", 7, "Gibbon", female),
}
func main() {
filteredPrimates := koazee.StreamOf(primates).
Filter(func(primate *primate) bool {
return primate.age > 10 && primate.genre == female
}).Out().Val().([]*primate)
for _, primate := range filteredPrimates {
fmt.Printf("%s is a female and is %d years\n", primate.name, primate.age)
}
}