Last active
August 29, 2015 14:04
-
-
Save tkfm-yamaguchi/38223d0dfa4ed832b27a to your computer and use it in GitHub Desktop.
ruby implementation of golang's sieve routine example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://golang.jp/go_tutorial#index12 | |
package main | |
import "fmt" | |
func generate(ch chan int) { | |
for i := 2; ; i++ { | |
ch <- i | |
} | |
} | |
func filter(in, out chan int, prime int) { | |
for { | |
i := <-in | |
if i%prime != 0 { | |
out <- i | |
} | |
} | |
} | |
func main() { | |
ch := make(chan int) | |
go generate(ch) | |
for i := 0; i < 100; i++ { | |
prime := <-ch | |
fmt.Println(prime) | |
ch1 := make(chan int) | |
go filter(ch, ch1, prime) | |
ch = ch1 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Ruby implementation of sieve.go (http://golang.jp/go_tutorial#index12) | |
# | |
def generate | |
Fiber.new do | |
n = 2 | |
loop do | |
Fiber.yield(n) | |
n += 1 | |
end | |
end | |
end | |
def filter(fib, prime) | |
Fiber.new do | |
loop do | |
cand = fib.resume | |
if cand.modulo(prime).nonzero? | |
Fiber.yield(cand) | |
end | |
end | |
end | |
end | |
# Main | |
fib = generate | |
100.times do | |
prime = fib.resume | |
puts prime | |
fib = filter(fib, prime) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment