From d717978979a310c1fc915208db0fbab17c071d11 Mon Sep 17 00:00:00 2001 From: Tamer Tas Date: Thu, 15 Sep 2016 11:39:40 +0300 Subject: [PATCH] concurrency/generator: merge the source and the pattern files --- concurrency/generator.go | 24 ------------------------ concurrency/generator.md | 37 ++++++++++++++++++++++++++++++++++--- 2 files changed, 34 insertions(+), 27 deletions(-) delete mode 100644 concurrency/generator.go diff --git a/concurrency/generator.go b/concurrency/generator.go deleted file mode 100644 index 6e21bc4..0000000 --- a/concurrency/generator.go +++ /dev/null @@ -1,24 +0,0 @@ -package generator - -func Range(start int, end int, step int) chan int { - c := make(chan int) - - go func() { - result := start - for result < end { - c <- result - result = result + step - } - - close(c) - }() - - return c -} - -func main() { - // print the numbers from 3 through 47 with a step size of 2 - for i := range Range(3, 47, 2) { - println(i) - } -} diff --git a/concurrency/generator.md b/concurrency/generator.md index c80e015..92982e8 100644 --- a/concurrency/generator.md +++ b/concurrency/generator.md @@ -1,7 +1,38 @@ # Generator Pattern -[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time +[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time. -# Implementation and Example +## Implementation -You can find the implementation and usage in [generator.go](generator.go) +```go +func Count(start int, end int) chan int { + ch := make(chan int) + + go func(ch chan int) { + for i := start; i < end ; i++ { + // Blocks on the operation + ch <- result + } + + close(ch) + }(ch) + + return ch +} +``` + +## Usage + +```go +fmt.Println("No bottles of beer on the wall") + +for i := range Count(1, 99) { + fmt.Println("Pass it around, put one up,", i, "bottles of beer on the wall") + // Pass it around, put one up, 1 bottles of beer on the wall + // Pass it around, put one up, 2 bottles of beer on the wall + // ... + // Pass it around, put one up, 99 bottles of beer on the wall +} + +fmt.Println(100, "bottles of beer on the wall") +```