Jump to content

Generator/Exponential: Difference between revisions

add scala
m (→‎{{header|REXX}}: changed wording of "so many values" ==> "a specified number of values". -- ~~~~)
(add scala)
Line 1,338:
print "[", join(", ", @answer), "]\n";</lang>
 
Output: <pre>[529, 57657tt>next64()6, 625, 676, 784, 841, 900, 961, 1024, 1089]</pre>
=={{header|Perl 6}}==
As with Haskell, generators are disguised as lazy lists in Perl&nbsp;6.
Line 1,611:
 
If we change both programs to drop the first 1_000_020 values (output: <tt>[1000242014641, 1000244014884, 1000246015129, 1000248015376, 1000250015625, 1000252015876, 1000254016129, 1000256016384, 1000258016641, 1000260016900]</tt>), then the one-generator solution runs much faster than the three-generator solution on a machine with [[MRI]] 1.9.2.
 
=={{header|Scala}}==
<lang scala>object Generators {
def main(args: Array[String]): Unit = {
def squares(n:Int=0):Stream[Int]=(n*n) #:: squares(n+1)
def cubes(n:Int=0):Stream[Int]=(n*n*n) #:: cubes(n+1)
def filtered(s:Stream[Int], c:Stream[Int]):Stream[Int]={
if(s.head>c.head) filtered(s, c.tail)
else if(s.head<c.head) Stream.cons(s.head, filtered(s.tail, c))
else filtered(s.tail, c)
}
 
filtered(squares(), cubes()) drop 20 take 10 print
}
}</lang>
Here is an alternative filter implementation using pattern matching.
<lang scala>def filtered2(s:Stream[Int], c:Stream[Int]):Stream[Int]=(s, c) match {
case (sh#::_, ch#::ct) if (sh>ch) => filtered2(s, ct)
case (sh#::st, ch#::_) if (sh<ch) => sh #:: filtered2(st, c)
case (_#::st, _) => filtered2(st, c)
}</lang>
Output:
<pre>529, 576, 625, 676, 784, 841, 900, 961, 1024, 1089, empty</pre>
 
=={{header|Scheme}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.