Generator/Exponential: Difference between revisions
Content added Content deleted
m (→{{header|REXX}}: added more comments to the REXX code. -- ~~~~) |
(Added code for C#) |
||
Line 661: | Line 661: | ||
29: 1089 |
29: 1089 |
||
</pre> |
</pre> |
||
=={{header|C sharp}}== |
|||
Note that types have been made static and variables made explicit as an aid to understanding. |
|||
'''Closure Style''' |
|||
<lang csharp>using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
namespace RosettaGenerator |
|||
{ |
|||
class ClosureStyle |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
Func<int> squaresGenerator = PowerGeneratorAsClosure(2); |
|||
Func<int> cubesGenerator = PowerGeneratorAsClosure(3); |
|||
Func<int> filter = FilterAsClosure(squaresGenerator, cubesGenerator); |
|||
foreach (int i in Enumerable.Range(0, 20)) |
|||
filter(); |
|||
foreach (int i in Enumerable.Range(21, 10)) |
|||
Console.Write(filter() + " "); |
|||
Console.WriteLine(); |
|||
} |
|||
public static Func<int> PowerGeneratorAsClosure(int exponent) |
|||
{ |
|||
int x = 0; |
|||
return () => { return (int)Math.Pow(x++, exponent); }; |
|||
} |
|||
public static Func<int> FilterAsClosure(Func<int> squaresGenerator, Func<int> cubesGenerator) |
|||
{ |
|||
int value; |
|||
int filter = cubesGenerator(); |
|||
return () => |
|||
{ |
|||
while (true) |
|||
{ |
|||
value = squaresGenerator(); |
|||
while (value > filter) |
|||
filter = cubesGenerator(); |
|||
if (value < filter) |
|||
return value; |
|||
} |
|||
}; |
|||
} |
|||
} |
|||
}</lang> |
|||
'''List Style''' |
|||
<lang csharp>using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
namespace RosettaGenerator |
|||
{ |
|||
class ListStyle |
|||
{ |
|||
static void Main(string[] args) |
|||
{ |
|||
IEnumerator<int> squaresGenerator = PowerGeneratorAsList(2); |
|||
IEnumerator<int> cubesGenerator = PowerGeneratorAsList(3); |
|||
IEnumerable<int> filter = FilterAsList(squaresGenerator, cubesGenerator); |
|||
foreach (int value in filter.Skip(20).Take(10)) |
|||
Console.Write(value + " "); |
|||
Console.WriteLine(); |
|||
} |
|||
public static IEnumerator<int> PowerGeneratorAsList(int exponent) |
|||
{ |
|||
int x = 0; |
|||
while (true) |
|||
yield return (int)Math.Pow(x++, exponent); |
|||
} |
|||
public static IEnumerable<int> FilterAsList(IEnumerator<int> squaresGenerator, IEnumerator<int> cubesGenerator) |
|||
{ |
|||
int value; |
|||
int filter = cubesGenerator.Current; |
|||
while (true) |
|||
{ |
|||
value = squaresGenerator.Current; |
|||
while (value > filter) |
|||
{ |
|||
cubesGenerator.MoveNext(); |
|||
filter = cubesGenerator.Current; |
|||
} |
|||
if (value < filter) |
|||
yield return value; |
|||
squaresGenerator.MoveNext(); |
|||
} |
|||
} |
|||
} |
|||
}</lang> |
|||
Output (for either): |
|||
<pre>529 576 625 676 784 841 900 961 1024 1089</pre> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |