Recursive Lambdas
At PDC several years ago, I attended the first talk on C# 3.0 by Anders Hejlsberg wherein he demonstrated LINQ and the new lambda syntax for C#. In the QA, I asked if it there was or could be a syntax for recursive lambda expressions. The answer was a “hadn’t really considered that".
The problem is that lambda expressions in C# are anonymous, so there is no way to call yourself since you don’t know your own name. At the initial Q/A session, it seemed to me that using or reusing a keyword would be a way to do that:
x => x < 2 ? 1 : x * this(x - 1); // or self or me or whatever
and the keyword magically means “the unpronounceable name of the currently scoped lambda expression”. This works in some cases, but is really a bad way to do it since once you’ve opened the door for one lambda expression, you should be able to have subexpressions and be able to recurse to the right one unambiguously.
The solution, which is covered here, here, and here, is to use a temporary variable to hold your lambda expression, initialized to null:
Func<int, int> f = null;
f = x => x < 2 ? 1 : x * f(x - 1);
which to me is really syntactic vinegar for Scheme’s letrec. It works, but it bugs me. I think I would prefer it if the formal parameters in a lambda expression could come with an optional name so that the anonymity could get stripped away to a certain degree.
The larger question has nothing to do with syntax: why the hell do I need recursive lambda expressions anyway? I’ve thought about this a lot and of course the correct answer is “you don’t”. There is no real need except to satisfy my inner CS junkie that wants to have complete and sweet lambda calculus embedded in the larger language. That’s the time to just let it go. Let C# be what C# is good at and let F#, Scheme, Haskell, et al be good at what they do.
Yes, I was considering seeing how much of ML could be embedded within C# just through lambdas and then I regained my sanity.