Sunday, April 8, 2012

Several days ago we've arrived to the blog "Recursive lambda expressions". There, author asks how to write a lambda expression that calculates a factorial (only expression statements are allowed).

The problem by itself is rather artificial, but at times you feel an intellectual pleasure solving such tasks by yourself. So, putting original blog post aside we devised our answers. The shortest one goes like this:

1. As C# lambda expression cannot refer to itself, so it have to receive itself as a parameter, so:
`factorial(factorial, n) = n <= 1 ? 1 : n * factorial(factorial, n - 1);`
2. To define such lambda expression we have to declare a delegate type that receives a delegate of the same type:
`delegate int Impl(Impl impl, int n);`
Fortunately, C# allows this, but a workaround could be used even if it were not possible.

3. To simplify the reasoning we've defined a two-expression version:
```Impl impl = (f, n) => n <= 1 ? 1 : n * f(f, n - 1); Func<int, int> factorial = i => impl(impl, i);```
4. Finally, we've written out a one-expression version:
```Func<int, int> factorial = i => ((Func<Impl, int>)(f => f(f, i)))((f, n) => n <= 1 ? 1 : n * f(f, n - 1)); ```
5. The use is:
`var f = factorial(10);`

After that excercise we've returned back to original blog and compared solutions. We can see that author appeals to a set theory but for some reason his answer is more complex than nesessary, but comments contain variants that analogous to our answer.

Sunday, April 8, 2012 9:18:29 AM UTC      Comments [0] -
.NET | Tips and tricks
All comments require the approval of the site owner before being displayed.
 Name E-mail Home page Remember Me Comment (Some html is allowed: `a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u`) where the @ means "attribute." For example, you can use or
. Enter the code shown (prevents robots): Live Comment Preview
Archive
 < January 2022 >
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
303112345
Categories
 .NET Angular AngularJS Announce ASP.NET Azure BizTalk Server C++ Incremental Parser Java javascript JSF and Facelets kendoui ML.NET SCCBridge SQL Server puzzle Thinking aloud Tips and tricks Window Search xslt
Blogroll
Statistics
Total Posts: 380
This Year: 1
This Month: 1
This Week: 0