Press "Enter" to skip to content

Unbelievable but true, chapter 1

I have such a colleague, let’s call him a footballer with a guitar because he wanted to be anonymous (but he allowed the publication of tasks and solutions).
At some point, he went to the board and wrote “Sum (1) (2) (3) ()) -> has to return the number” and said that we have 10 minutes from now. He also mentioned that it has the potential to be a recruitment task for seniors, because you have to think a little outside the box.

It seems impossible? I thought so too. Solutions have been delivered in 2 languages.

And the answer looks like this:

[C#]

        private delegate dynamic F(int x = 0);

        private static dynamic Sum(int n = 0)
        {
            if (n == 0)
            {
                return 0;
            }
            F f = x => x == 0 ? n : Sum(x + n);
            return f;
        }
            Console.WriteLine(Sum());
            Console.WriteLine(Sum(1)());
            Console.WriteLine(Sum(1)(2)());
            Console.WriteLine(Sum(1)(2)(3)());

——————–

[PY]
def sum(n = None):
    if n == None:
        return 0
    return lambda x = None: n if x == None else sum(n + x)
print(sum(1)(2)(3)())