github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/talks/2013/go4python/genex2.go (about) 1 // +build OMIT 2 3 package main 4 5 import "fmt" 6 7 // prime returns true if n is a prime number. 8 func prime(n int) bool { 9 for i := 2; i < n; i++ { 10 if n%i == 0 { 11 return false 12 } 13 } 14 return true 15 } 16 17 // fib returns a channel on which the first n Fibonacci numbers are written. 18 func fib(n int) chan int { 19 c := make(chan int) 20 go func() { 21 a, b := 0, 1 22 for i := 0; i < n; i++ { 23 a, b = b, a+b 24 c <- a 25 } 26 close(c) 27 }() 28 return c 29 } 30 31 // filterPrimes returns a channel of ints on which it writes all the prime 32 // numbers read from cin, and closes the returned channel when cin is closed. 33 func filterPrimes(cin chan int) chan int { 34 cout := make(chan int) 35 go func() { 36 for v := range cin { 37 if prime(v) { 38 cout <- v 39 } 40 } 41 close(cout) 42 }() 43 return cout 44 } 45 46 func main() { 47 for p := range filterPrimes(fib(20)) { 48 fmt.Println(p) 49 } 50 }