Generator/Exponential: Difference between revisions
Content added Content deleted
(Go solution) |
(→{{header|Go}}: changes to meet task description) |
||
Line 54: | Line 54: | ||
println()</lang> |
println()</lang> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
Generators can be implemented directly in Go by a channel fed by a goroutine. |
|||
Go channels and goroutines implement generators directly. |
|||
Thus a "function returning a generator" corresponds to a function that creates a channel, starts a goroutine that will send values on the channel, and returns the channel. The function powCh does this, starting a function literal as the goroutine. The returned channel corresponds to a generator. |
|||
The "generator that filters..." is implemented without an extra function, simply by creating the channel and starting a (previously declared) function as a goroutine. Here too, the created channel, chF, corresponds to a generator, once the goroutine has be started for it. |
|||
<lang go>package main |
<lang go>package main |
||
import |
import ( |
||
⚫ | |||
"math" |
|||
) |
|||
// note: exponent not limited to ints |
|||
func genSquares(ch chan<- int) { |
|||
func powCh(e float64) <-chan float64 { |
|||
⚫ | |||
ch := make(chan float64) |
|||
go func() { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
}() |
|||
return ch |
|||
} |
} |
||
func |
func genMonotonicIncA_NotMonotonicIncB(outCh chan<- float64, |
||
aCh, bCh <-chan float64) { |
|||
for i := 0; ; i++ { |
|||
⚫ | |||
⚫ | |||
⚫ | |||
// this long function name to indicate that the filtering |
|||
// logic works only because squares and cubes are both |
|||
// monotonically increasing over the (presumed) domain |
|||
⚫ | |||
func genMonotonicIncA_NotMonotonicIncB(outCh chan<- int, aCh, bCh <-chan int) { |
|||
for a, b := <-aCh, <-bCh; ; { |
for a, b := <-aCh, <-bCh; ; { |
||
if a > b { |
if a > b { |
||
Line 88: | Line 92: | ||
func main() { |
func main() { |
||
// square and cube generators |
|||
⚫ | |||
chSq := powCh(2) |
|||
chCu := |
chCu := powCh(3) |
||
go genCubes(chCu) |
|||
// filtered generator (in two lines) |
|||
chF := make(chan int) |
|||
⚫ | |||
go genMonotonicIncA_NotMonotonicIncB(chF, chSq, chCu) |
go genMonotonicIncA_NotMonotonicIncB(chF, chSq, chCu) |
||
for i := 0; i < 20; i++ { |
for i := 0; i < 20; i++ { |
||
<-chF |
<-chF |
||
Line 101: | Line 107: | ||
} |
} |
||
fmt.Println("") |
fmt.Println("") |
||
⚫ | |||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |