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.
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
 
import "fmt"(
}"fmt"
"math"
)
 
// note: exponent not limited to ints
func genSquares(ch chan<- int) {
func powCh(e float64) <-chan float64 {
for i := 0; ; i++ {
ch <- i:= *make(chan ifloat64)
}go func() {
// generate powers of non-negative integers.
for i := float64(0); ; i++ {
ch <- math.Pow(i, * i * ie)
}
}()
return ch
}
 
func genCubesgenMonotonicIncA_NotMonotonicIncB(choutCh chan<- int) {float64,
aCh, bCh <-chan float64) {
for i := 0; ; i++ {
ch <- i * i * 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
// of non-negative integers.
func genMonotonicIncA_NotMonotonicIncB(outCh chan<- int, aCh, bCh <-chan int) {
for a, b := <-aCh, <-bCh; ; {
if a > b {
Line 88 ⟶ 92:
 
func main() {
// square and cube generators
chSq := make(chan int)
gochSq genSquares:= powCh(chSq2)
chCu := makepowCh(chan int3)
 
go genCubes(chCu)
// filtered generator (in two lines)
chF := make(chan int)
chSqchF := make(chan intfloat64)
go genMonotonicIncA_NotMonotonicIncB(chF, chSq, chCu)
 
for i := 0; i < 20; i++ {
<-chF
Line 101 ⟶ 107:
}
fmt.Println("")
}</lang>
Output:
<pre>
1,707

edits