package kata // Based on the Go classical concurrent prime sieve // See https://golang.org/test/chan/sieve1.go func Primes(limit int) []int { // Generate numbers from 2 to limit, included. gen := func(ch chan<- int, limit int) { for i := 2; i <= limit; i++ { ch <- i } close(ch) } // Remove divisible numbers // - in: numbers source // - out: numbers sink // - prime: prime by which to attempt modulo filter := func(in <-chan int, out chan<- int, prime int) { for { candidate, ok := <-in // Source was closed. if !ok { break } if candidate%prime != 0 { out <- candidate } } close(out) } genChan := make(chan int) go gen(genChan, limit) var primes []int for i := 0; ; i++ { prime, ok := <-genChan if !ok { break } primes = append(primes, prime) filterChan := make(chan int) go filter(genChan, filterChan, prime) genChan = filterChan } return primes }