Book Image

Functional C#

Book Image

Functional C#

Overview of this book

Functional programming makes your application faster, improves performance, and increases your productivity. C# code is written at a higher level of abstraction, so that code will be closer to business requirements, abstracting away many low-level implementation details. This book bridges the language gap for C# developers by showing you how to create and consume functional constructs in C#. We also bridge the domain gap by showing how functional constructs can be applied in business scenarios. We’ll take you through lambda expressions and extension methods, and help you develop a deep understanding of the concepts and practices of LINQ and recursion in C#. By the end of the book, you will be able to write code using the best approach and will be able to perform unit testing in functional programming, changing how you write your applications and revolutionizing your projects.
Table of Contents (19 chapters)
Functional C#
Credits
About the Author
Acknowledgments
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

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