I am trying to solve a question on Codewars and one thing I didn't realize earlier came up:
public class Kata
{
private static int y(int x) => 2 * x + 1;
private static int z(int x) => 3 * x + 1;
private static int self(int x) => x;
public static int DblLinear(int n)
{
Func<int, int> lowerBound = self;
Func<int, int> upperBound = self;
int result = 1;
for (int i = 1; i <= n; ++i)
{
lowerBound = (x) => y(lowerBound(x)); // [1]
upperBound = (x) => z(upperBound(x)); // [2]
}
...
}
}
My intention was to calculate y(y(y(y(... (x))))
and z(z(z(z(... (x))))
iteratively, but lowerBound
and upperBound
do not appear to function as actual variables; they work more like delegates here. When I run the program, a StackOverflowException is thrown.
Is there any way I can accomplish this?
lowerBound
andupperBound
, in the lambda itself, rather than those actual variables. See duplicate.