# How should I submit an anonymous lambda that has a self reference?

In a lot of situations we allow for C# answers to simply be an anonymous lambda with the assumption that to run it it needs to be stored in a variable.

So given that, is it acceptable to also assume that the variable have a specific name so that it can call itself?

An example using Fibonacci:

//Boilerplate
Func<int,int> f = ()=> {};
f=
//golfed function
n=>n<2?1:f(n-1)+f(n-2);


If the lambda needs a specific name to work (because you're calling it recursively), then you'll have to count the declaration and definition of that name, I'm afraid. So it'll have to be something like

Func<int,int>f=n=>n<2?1:f(n-1)+f(n-2);


Not entirely sure if that requires some additional space somewhere. I'm also not sure whether the compiler would accept var there as the type, but in any case, you'll have to count all the code that's required to make the answer work and declare the necessary names.

Note that not all languages require named functions for recursion. For example, in Mathematica, you can refer to the nearest surrounding unnamed function with #0, which means that

If[#<2,1,#0[#-1]+#0[#-2]]&


would be a valid submission, because here a name is not required to make the function work. (That said, I think a named function would actually be shorter, but that's beside the point.)

• So the interesting thing about your second paragraph is that in C# you can't use the var keyword for anonymous lambdas so one could argue that the typed variable is required to consider it 'working', and yes a named function would indeed by shorter in this case. – user19547 Oct 20 '16 at 21:08
• Note that the code sample here won't compile, because C# will insist you assign f before using it in the lambda. For example Func<int, int> f = null; f = n => n < 2 ? 1 : f(n - 1) + f(n - 2); – VisualMelon Jan 9 '17 at 17:39
• @VisualMelon Of course! So there's little use for recursive lambdas now :| – adrianmp Sep 11 '18 at 6:40

I don't include the declaration in the byte count, however you need the function name because it's recursive, so the code size should be calculated on this snippet:

f=n=>n<2?1:f(n-1)+f(n-2);


Func<int,int>f=null;f=n=>n<2?1:f(n-1)+f(n-2);

Which means there's little use for recursive lambda functions. The classic version is 41 bytes:
int f(int n){return n<2?1:f(n-1)+f(n-2);}