I visited this site a few days ago in the "Anonymous Recursion in C #" section. The essence of the article is that the following code will not work in C #:
Func<int, int> fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
The rest of the article details the use of currying and Y-combinator to return to "Anonymous recursion" in C #. This is quite interesting, but it is a complex complex for my everyday encoding, I'm afraid. At the moment, at least ...
I like to see the material for myself, so I opened the Mono CSharp REPL and entered this line. No mistakes. So, I introduced fib(8); . To my great surprise, it worked! REPL answered with 21 !
I thought that maybe it was some kind of magic with REPL, so I activated "vi", typed in the following program and compiled it.
using System; public class Program { public static void Main(string[] args) { int x = int.Parse(args[0]); Func<int, int> fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n; Console.WriteLine(fib(x)); } }
He built and did a great job too!
I am running Mono 2.10 on a Mac. I do not have access to the Windows machine right now, so I can not check this on .NET in Windows.
Was it fixed on .NET, or is it a quiet Mono feature? The article is a couple of years.
If this is only Mono, I canβt wait for the next interview where they ask me to write the Fibinocci function in my language of choice (Mono C #), where I must provide a warning that .NET will not work. Well, actually I can wait, because I love my job. However, interesting ...
Update:
Mono does not perform anonymous recursion because it uses fib as a named delegate. To blame. The fact that the Mono C # compiler is null for fib before the assignment will be an error, as indicated below. I say βcompilerβ because the .NET CLR starts the resulting assembly just fine, even if the .NET C # compiler will not compile the code.
For the entire Nazi interview there:
Func<int, int> fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;
can be replaced with an iterative version:
Func<int, int> fib = n => { int old = 1; int current = 1; int next; for (int i = 2; i < n; i++) { next = current + old; old = current; current = next; } return current; };
You might want to do this because the recursive version is inefficient in C #. Some may suggest using memoization , but since it is still slower than the iterative method, they may just be wankers. :-)
At this point, it becomes more of an advertisement for functional programming than anything else (since the recursive version is much nicer). This really has nothing to do with my original question, but some answers thought this was important.