Skip to content

Instantly share code, notes, and snippets.

@md2perpe
Last active March 23, 2016 16:18
Show Gist options
  • Save md2perpe/f17cd61766ea5bda04b3 to your computer and use it in GitHub Desktop.
Save md2perpe/f17cd61766ea5bda04b3 to your computer and use it in GitHub Desktop.
package main
import "fmt"
// Sends the sequence n, n+1, n+2, ... to the `out` channel
func from(n int, out chan<- int) {
for i := n; ; i++ {
out <- i
}
}
// Reads from the `in` channel and sends only those numbers
// that satisfy the predicate `pred` to the `out` channel
func filter(in <-chan int, out chan<- int, pred func (int) bool) {
for n := range in {
if pred(n) {
out <- n
}
}
}
// Implements Sieve of Eratosthenes
// by creating a chain of sieves, one for each found prime
func sieve(numbers <-chan int, primes chan<- int) {
// Get first number; that's a prime
p := <-numbers
primes <- p
// Send sifted numbers to next sieve
// through channel `filtered`
filtered := make(chan int)
go sieve(filtered, primes)
filter(numbers, filtered, func (n int) bool {
return n % p != 0
})
}
// Reads from the `primes` channel and prints to console
func output(primes chan int) {
for p := range primes {
fmt.Printf("%d\n", p)
}
}
// The main function
func main() {
// Create channels;
// `numbers` for unsifted numbers
// `primes` for primes
numbers := make(chan int)
primes := make(chan int)
// Start first sieve
go sieve(numbers, primes)
// Start reading and printing primes
go output(primes)
// Feed unsifted numbers 2, 3, 4, 5, ... into `numbers`
from(2, numbers)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment