C# solution to g()(“al”)

Here is a fun coding problem. The idea is simple. g()(“al”) outputs “goal”. g()()(“al”) outputs “gooal”. And so on. So here is what it comes down to. A call to g(), needs to return either a function, or a string. Sounds simple enough. In C# you can get it done with heavy use of the ‘dynamic’ type, and a delegate.

namespace Goal
    using System;
    class Program
        static void Main(string[] args)
        delegate dynamic g(string a = "o");
        static dynamic G(string o = "o", string curr = "g")
            return o == "al" ? (dynamic)curr + o : new g((a) => G(a, curr + o));

There we have it! The output will be something like:

  • goal
  • gooal
  • goooal
  • gooooal
  • goooooal

Leave a Reply

Your email address will not be published. Required fields are marked *