Skip to content

Instantly share code, notes, and snippets.

@maiah
Created October 19, 2015 07:45
Show Gist options
  • Save maiah/49579f8ca439c52e825a to your computer and use it in GitHub Desktop.
Save maiah/49579f8ca439c52e825a to your computer and use it in GitHub Desktop.
Streaming Reduce, Map, and Collect in Go
package main
import (
"fmt"
"strconv"
)
type Power struct {
up int
}
func main() {
s := []int{2, 3, 5, 7, 11, 13}
fmt.Println("s ==", s)
// Filter
f := func(nums []int) <-chan int {
dest := make(chan int)
go func() {
for _, v := range nums {
if v > 3 && v < 13 {
dest <- v
}
}
close(dest)
}()
return dest
}(s[0:])
// Map
m := func(y <-chan int) <-chan Power {
dest := make(chan Power)
go func() {
for v := range y {
dest <- Power{v}
}
close(dest)
}()
return dest
}(f)
// Collect
res := func(x <-chan Power) string {
powers := "The powers: "
pow := 0
for v := range x {
pow += v.up
}
return powers + strconv.Itoa(pow)
}(m)
fmt.Println(res)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment