Generator/Exponential: Difference between revisions
→{{header|Go}}: changes to meet task description
(Go solution) |
(→{{header|Go}}: changes to meet task description) |
||
Line 54:
println()</lang>
=={{header|Go}}==
Generators can be implemented directly in Go by a channel fed by a goroutine.
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
import
"math"
)
// note: exponent not limited to ints
func powCh(e float64) <-chan float64 {
for i := 0; ; i++ {▼
▲ for i := float64(0); ; i++ {
}
}()
return ch
}
func
aCh, bCh <-chan float64) {
▲ ch <- i * i * i
▲ }
}▼
▲// of non-negative integers.
for a, b := <-aCh, <-bCh; ; {
if a > b {
Line 88 ⟶ 92:
func main() {
// square and cube generators
chSq := make(chan int)▼
chCu :=
// filtered generator (in two lines)
go genMonotonicIncA_NotMonotonicIncB(chF, chSq, chCu)
for i := 0; i < 20; i++ {
<-chF
Line 101 ⟶ 107:
}
fmt.Println("")
▲}
Output:
<pre>
|