2
\$\begingroup\$

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); 
\$\endgroup\$
0

2 Answers 2

9
\$\begingroup\$

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.)

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$
    – user19547
    Commented Oct 20, 2016 at 21:08
  • \$\begingroup\$ 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); \$\endgroup\$ Commented Jan 9, 2017 at 17:39
  • \$\begingroup\$ @VisualMelon Of course! So there's little use for recursive lambdas now :| \$\endgroup\$
    – adrianmp
    Commented Sep 11, 2018 at 6:40
2
\$\begingroup\$

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);

Leading to 25 bytes.

The verbose, working version is 45 bytes:

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);}
\$\endgroup\$

You must log in to answer this question.