Generator/Exponential: Difference between revisions
Content added Content deleted
(Wrote a draft task on generators) |
(→Tcl: Added implementation) |
||
Line 4: | Line 4: | ||
* http://en.wikipedia.org/wiki/Generator_(computer_science) |
* http://en.wikipedia.org/wiki/Generator_(computer_science) |
||
'''Task:''' Write a generator (or generators), in the most natural way in your language, that produces the numbers that are squares (<math>n^2</math>) but not cubes (<math>m^3</math>) and use that to print the first |
'''Task:''' Write a generator (or generators), in the most natural way in your language, that produces the numbers that are squares (<math>n^2</math>) but not cubes (<math>m^3</math>) and use that to print the first 21st to 30th members of that sequence. |
||
=={{header|Tcl}}== |
|||
{{works with|Tcl|8.6} |
|||
<lang tcl>package require Tcl 8.6 |
|||
proc powers m { |
|||
yield |
|||
for {set n 0} true {incr n} { |
|||
yield [expr {$n ** $m}] |
|||
} |
|||
} |
|||
coroutine squares powers 2 |
|||
coroutine cubes powers 3 |
|||
coroutine filtered apply {{s1 s2} { |
|||
yield |
|||
set f [$s2] |
|||
set v [$s1] |
|||
while true { |
|||
if {$v > $f} { |
|||
set f [$s2] |
|||
continue |
|||
} elseif {$v < $f} { |
|||
yield $v |
|||
} |
|||
set v [$s1] |
|||
} |
|||
}} squares cubes |
|||
for {set i 0} {$i<20} {incr i} {filtered} |
|||
for {} {$i<30} {incr i} { |
|||
puts [filtered] |
|||
}</lang> |
|||
Output: |
|||
<pre> |
|||
529 |
|||
576 |
|||
625 |
|||
676 |
|||
784 |
|||
841 |
|||
900 |
|||
961 |
|||
1024 |
|||
1089 |
|||
</pre> |