Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Functional C#

You're reading from   Functional C# Uncover the secrets of functional programming using C# and change the way you approach your applications

Arrow left icon
Product type Paperback
Published in Dec 2016
Publisher Packt
ISBN-13 9781785282225
Length 370 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Wisnu Anggoro Wisnu Anggoro
Author Profile Icon Wisnu Anggoro
Wisnu Anggoro
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Tasting Functional Style in C# 2. Walkthrough Delegates FREE CHAPTER 3. Expressing Anonymous Methods with Lambda Expressions 4. Extending Object Functionality with Extension Methods 5. Querying Any Collection Easily with LINQ 6. Enhancing the Responsiveness of the Functional Program with Asynchronous Programming 7. Learning Recursion 8. Optimizing the Code using Laziness and Caching Techniques 9. Working with Pattern 10. Taking an Action in C# Functional Programming 11. Coding Best Practice and Testing the Functional Code

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

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image