From 89df9f09556078483358422823f2ec1de2966182 Mon Sep 17 00:00:00 2001 From: mehdy Date: Wed, 7 Sep 2016 11:18:35 +0430 Subject: [PATCH] concurrency/generator: refactor generator pattern --- concurrency/generator.go | 24 ++++++++++++++++++++++++ concurrency/generator.md | 5 +++-- 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 concurrency/generator.go diff --git a/concurrency/generator.go b/concurrency/generator.go new file mode 100644 index 0000000..6e21bc4 --- /dev/null +++ b/concurrency/generator.go @@ -0,0 +1,24 @@ +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 2161248..c80e015 100644 --- a/concurrency/generator.md +++ b/concurrency/generator.md @@ -1,6 +1,7 @@ # Generator Pattern -[Generator](https://en.wikipedia.org/wiki/Generator_(computer_programming)) is a special routine that can be used to control the iteration behavior of a loop. +[Generators](https://en.wikipedia.org/wiki/Generator_(computer_programming)) yields a sequence of values one at a time # Implementation and Example -With Go language, we can implement generator in two ways: channel and closure. Fibonacci number generation example can be found in [generators.go](generators.go). \ No newline at end of file + +You can find the implementation and usage in [generator.go](generator.go)