Recursion in a functional approach using LINQ Aggregate
When we deal with a factorial formula, we can use LINQ Aggregate to refactor our recursive function into a functional approach. LINQ Aggregate will accumulate the given sequence, and then we will have the result of the recursion from the accumulator. In Chapter 1, Tasting Functional Style in C# we have already done this refactoring. Let's borrow the code from the chapter to analyze the use of the Aggregate
method. The following code will use the Aggregate
method, which we can find in the RecursionUsingAggregate.csproj
project:
public partial class Program { private static void GetFactorialAggregate(int intNumber) { IEnumerable<int> ints = Enumerable.Range(1, intNumber); int factorialNumber = ints.Aggregate((f, s) => f * s); Console.WriteLine("{0}! (using Aggregate) is {1}", intNumber, factorialNumber); } }
If we run...