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: - 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);` - 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);`
- 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); - 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));` - 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. |
Navigation
Archive
Categories
Blogroll
Disclaimer
The opinions expressed herein are our own personal opinions and do not represent
our employer's view in anyway.
© 2016, Nesterovsky bros |

All Content © 2016, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou) |

`a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u`

) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.Enter the code shown (prevents robots):