0

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?

  • Just use variables scoped to the loop body, copied from `lowerBound` and `upperBound`, in the lambda itself, rather than those actual variables. See duplicate. – Peter Duniho Jan 18 '21 at 16:44

1 Answers1

2

The problem that you have is that a lambda is a closure over a variable. If you change the variable, you change the behavior of the lambda.

The solution is that you need to create an array of functions, where each one is pointing at the previous entry in the array. Now each function has its own variable to close over, and you avoid the infinite loop.

btilly
  • 43,296
  • 3
  • 59
  • 88