The Go Programming Language

Source file doc/progs/sieve1.go

     1	// Copyright 2009 The Go Authors. All rights reserved.
     2	// Use of this source code is governed by a BSD-style
     3	// license that can be found in the LICENSE file.
     4	
     5	package main
     6	
     7	import "fmt"
     8	
     9	// Send the sequence 2, 3, 4, ... to returned channel 
    10	func generate() chan int {
    11		ch := make(chan int)
    12		go func() {
    13			for i := 2; ; i++ {
    14				ch <- i
    15			}
    16		}()
    17		return ch
    18	}
    19	
    20	// Filter out input values divisible by 'prime', send rest to returned channel
    21	func filter(in chan int, prime int) chan int {
    22		out := make(chan int)
    23		go func() {
    24			for {
    25				if i := <-in; i%prime != 0 {
    26					out <- i
    27				}
    28			}
    29		}()
    30		return out
    31	}
    32	
    33	func sieve() chan int {
    34		out := make(chan int)
    35		go func() {
    36			ch := generate()
    37			for {
    38				prime := <-ch
    39				out <- prime
    40				ch = filter(ch, prime)
    41			}
    42		}()
    43		return out
    44	}
    45	
    46	func main() {
    47		primes := sieve()
    48		for i := 0; i < 100; i++ { // Print the first hundred primes.
    49			fmt.Println(<-primes)
    50		}
    51	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.