Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

Functional C#
Functional C#
Functional C#
Ebook667 pages4 hours

Functional C#

Rating: 5 out of 5 stars

5/5

()

Read preview

About this ebook

This book is suitable for C# developers with basic prior knowledge of C# and with no functional programming experience at all.
LanguageEnglish
Release dateDec 30, 2016
ISBN9781785881039
Functional C#

Related to Functional C#

Related ebooks

Programming For You

View More

Related articles

Reviews for Functional C#

Rating: 5 out of 5 stars
5/5

1 rating0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Functional C# - Anggoro Wisnu

    Table of Contents

    Functional C#

    Credits

    About the Author

    Acknowledgments

    About the Reviewer

    www.PacktPub.com

    Why subscribe?

    Customer Feedback

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. Tasting Functional Style in C#

    Introducing functional programming

    Understanding definitions, scripts, and sessions

    Using substitution and simplification to evaluate the expression

    Understanding the functions used for functional programming

    Forming the definition

    Currying

    Comparison between functional and imperative programming

    Preparing the C# compiler

    Concepts of functional programming

    First-class and higher-order functions

    Function types

    Function values

    Pure functions

    Recursive functions

    Feeling functional in C#

    Using mathematical concept to understand functional approach

    Applying tuple for functional C#

    Currying in C#

    Pipelining

    Method chaining

    Transforming imperative code to functional code

    The imperative code approach

    The functional code approach

    The GenerateOrderedList() method

    The Main() method

    The advantages and disadvantages of functional programming

    Summary

    2. Walkthrough Delegates

    Introducing delegates

    Simple delegates

    Multicast delegates

    Using the Delegate.Combine() and Delegate.Remove() methods

    Using += and -= operators

    Built-in delegates

    Generic delegates

    The Action and Func delegates

    Distinguishing variance in delegates

    Covariance

    Contravariance

    Summary

    3. Expressing Anonymous Methods with Lambda Expressions

    Getting to know anonymous methods

    Creating anonymous methods

    Using an anonymous method as an argument

    Writing anonymous methods - some guidelines

    Advantages of the anonymous methods

    Lambda expressions

    Transforming an anonymous method to a lambda expression

    Creating a delegate type using lambda expresions

    Expression trees and lambda expressions

    Subscribing for events using lambda expressions

    Using the event keyword

    Using EventHandler or EventHandler

    The advantages of using lambda expression in functional programming

    First-class functions

    Closure

    Summary

    4. Extending Object Functionality with Extension Methods

    Getting closer to extension methods

    Creating an extension method

    Extension methods in the code IntelliSense

    Calling extension methods in the other assemblies

    Referencing a namespace

    Piggybacking a namespace

    Leveraging the interface, collection, and object

    Extending the interface

    Extending the collection

    Extending an object

    Advantages of using extension methods in functional programming

    Limitations of the extension method

    Extending a static class

    Modifying the method implementation in the existing class or type

    Summary

    5. Querying Any Collection Easily with LINQ

    Getting started with LINQ

    Deferring LINQ execution

    Choosing between fluent syntax and query expression syntax

    Understanding the LINQ fluent syntax

    Understanding the LINQ query expression syntax

    Enumerating standard query operators

    Filtering

    Projection

    Joining

    Ordering

    Grouping

    The set operation

    Conversion methods

    Element operation

    Summary

    6. Enhancing the Responsiveness of the Functional Program with Asynchronous Programming

    Building a responsive application

    Running a program synchronously

    Applying threads in the program

    Creating threads using thread pool

    The asynchronous programming model pattern

    Using the synchronous Read() method

    Using the BeginRead() and EndRead() methods

    Adding LINQ to the BeginRead() method invocation

    The task-based asynchronous pattern

    Introducing the Task and Task classes

    Applying a simple TAP model

    Using the WhenAll() extension method

    Wrapping an APM into a TAP model

    Asynchronous programming with the async and await keywords

    Asynchronous functions in functional programming

    Summary

    7. Learning Recursion

    Exploring recursion

    Working of the recursive routine

    Refactoring an iteration to the recursion

    Using tail recursion

    Accumulator-passing style

    Continuation-passing style

    Indirect recursion over direct recursion

    Recursion in a functional approach using LINQ Aggregate

    Delving into the Aggregate method

    Summary

    8. Optimizing the Code using Laziness and Caching Techniques

    Introduction to laziness

    Lazy enumeration

    Lazy evaluation

    Nonstrict evaluation

    Lazy initialization

    The advantages and disadvantages of being lazy

    Caching expensive resources

    Performing initial computation

    Memoization

    Summary

    9. Working with Pattern

    Dissecting pattern matching in functional programming

    Transforming data using pattern matching

    Switching for pattern matching

    Simplifying pattern matching

    Welcoming the coming of pattern matching feature in C# 7

    Introducing Monad as a design pattern

    Creating the Monadic M type

    Implementing the generic data type to Monad

    Implementing Monad to Lazy and Task

    Rules of the Monad pattern

    Summary

    10. Taking an Action in C# Functional Programming

    Developing functional programming in Windows forms

    Creating the code behind a form

    Creating the engine code in an imperative approach

    Preparing class properties

    Constructing the constructor

    Clearing the properties

    Appending the number to the display box

    Preparing the mathematical operation

    Formatting the input

    Solving the calculation

    Calculating the additional operation

    Creating the engine code in the functional approach

    Adding several new properties

    Simplifying the pattern matching

    Assigning the properties

    Constructing the class by clearing the properties

    Appending the inputted number to the text box

    Preparing the operation

    Formatting the input

    Solving the calculation

    Calculating the additional operation

    Summary

    11. Coding Best Practice and Testing the Functional Code

    Coding best practices in functional C#

    Preventing dishonest signatures

    Refactoring a mutable class into an immutable one

    Avoiding mutability and temporal coupling

    Dealing with the side-effects

    Separating the code from domain logic and mutable shell

    Examining the code containing side-effects

    Refactoring the AddRecord() method

    Refactoring the RemoveRecord() method

    Running domain logic in unit testing

    Testing the AddRecord() method

    Testing the RemoveRecord() method

    Executing the test

    Adding the mutable shell into code

    Summary

    Functional C#


    Functional C#

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: January 2017

    Production reference: 1281216

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B3 2PB, UK.

    ISBN 978-1-78528-222-5

    www.packtpub.com

    Credits

    About the Author

    Wisnu Anggoro is a Microsoft Certified Professional in C# programming and an experienced C/C++ developer. He has also authored Boost.Asio C++ Network Programming - Second Edition, published by Packt. He has been programming since he was in junior high school (about 20 years ago) and started developing computer applications using the BASIC programming language in the MS-DOS environment. He has a solid experience of smart card programming as well as desktop and web application programming, such as designing, developing, and supporting live use applications for SIM Card Operating System Porting, personalization, PC/SC communication, and other smart card applications that require the use of C# and C/C++. He is currently a senior smart card software engineer at CIPTA, an Indonesian company that specializes in the innovation and technology of smart cards. You can write to him at wisnu@anggoro.net.

    Acknowledgments

    First and above all, I praise God, the almighty, for providing me with this opportunity and granting me the capability to proceed successfully. To my wife, dear Vivin, without whose support and encouragements I could not have finished this book. Thank you for reminding me of the deadline of each chapter, so I could always stay on the writing process schedule. To my beloved sons, the source of my joy: Olav, who makes my life worth living by giving me much happiness, and Oliver, who was born just after I submitted the draft of chapter 5. His first cry boosted my spirit to finish this book. And a thank you to my parents and family for their inspiration.

    Also, I would like to express my gratitude to the following individuals who supported me in writing this book:

    The team at Packt, especially Denim Pinto, my acquisition editor, who invited me to author this book; Priyanka Mehta, my content development editor, for her constant effort in encouraging me to supply the best content for this book; and to all reviewers who have given input and suggestions to make the content of this book much better.

    My best mentor, teacher, and superior at CIPTA (www.cipta.com), Benediktus Dwi Desiyanto, who never let me stop learning new things and always encourages me to catch my dream. Hope this book can be the way to make all my dreams come true.

    Chief Executive Officer of CIPTA, Steven Chandra, for providing me with a new Amazon Kindle. Since then, the number of books I have read has increased. The insight from the books I have read was helpful while I wrote this book.

    Chief Human Capital Officer of CIPTA, Budi Setiawan, for appreciating my work in authoring my previous book and inviting me to join the C-MAG (CIPTA Magazine) press team. It helped me a lot in enhancing my writing skills.

    All my friends and colleagues at CIPTA, especially Muhammad Abdurochman Sanjaya and Seno Budi Utomo, for the insight of C# programming in developing a smart card application. It helped me develop the application I presented in this book. And Andre Tampubolon, for the insight of functional programming in Haskell.

    Dave Fancher, the author of The Book of F#, thank you for your amazing site, https://davefancher.com/, my one-stop place to learn functional programming. His website inspired my authoring of this book.

    About the Reviewer

    Haridas Nair works as a software architect within the Architecture Practice, providing both technical and solution architecture. He is responsibile for defining, documenting, and articulating functional and nonfunctional scope.

    He manages various project teams varying in size and location in USA, UK, and offshore (India). The day-to-day duties range from assisting in technical presales activities, responding to RFPs, through to high-level and detailed design phases to actual implementation on enterprise-scale projects.

    I would like to thank Praseed Pai for introducing me to this publisher. I would also like to thank the publisher for giving me this opportunity.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously--that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: customerreviews@packtpub.com.

    Preface

    Some of us may be used to developing an application using the object orientation programming technique and don’t care about the functional programming technique. However, there are benefits to using functional programming. One of the benefits is that we will get a new perspective on our programming code since the function in functional programming is identical to a mathematical function. Because it's identical to a mathematical function, the function in functional programming contains no side-effects, which means that the function invocation will have no effect on other functions in the class. We will discuss more details about the benefits and other things related to functional programming in this book.

    What this book covers

    Chapter 1, Tasting Functional Style in C#, introduces the functional programming approach by discussing its concepts and the comparison between functional and imperative programming. We also try to refactor a simple imperative code into a functional approach.

    Chapter 2, Walkthrough Delegates, covers the definition, syntax, and use of delegates. We also discuss the variance of delegates and the built-in delegate.

    Chapter 3, Expressing Anonymous Methods with Lambda Expressions, walks us through the concept of delegates and uses it to create and use an anonymous method. After we dig through the anonymous method, we can transform it into a lambda expression and then apply it to functional programming.

    Chapter 4, Extending Object Functionality with Extension Methods, elaborates the benefits of using the extension method in functional programming. Before that, we discuss the use of the extension method and also discuss how to get this new method in IntelliSense. Also, we try to invoke the extension method from other assemblies.

    Chapter 5, Querying Any Collection Easily with LINQ, enumerates the LINQ operator provided by C# and compares the two LINQ syntaxes: Fluent Syntax and Query Expression Syntax. We also discuss deferred execution in the LINQ process.

    Chapter 6, Enhancing the Responsiveness of the Functional Program with Asynchronous Programming, covers asynchronous programming for the functional approach. It will explain the Asynchronous Programming Model and the Task-based Asynchronous pattern.

    Chapter 7, Learning Recursion, explains the advantages of recursion over the loop sequence. We also discuss direct and indirect recursion in this chapter.

    Chapter 8, Optimizing the Code Using Laziness and Caching Techniques, covers the technique used to optimize the code in the functional approach. We talk about laziness thinking and the caching technique in order to optimize our code.

    Chapter 9, Working with Pattern, covers the advantages of using patterns compared to conventional switch-case operations. We discuss pattern matching and monad in this chapter. We use the pattern matching feature, which is the new feature provided by C# 7.

    Chapter 10, Taking an Action in C# Functional Programming, walks us through developing functional code based on given imperative code. We use our learning in the previous chapter to create an application using the functional approach.

    Chapter 11, Coding Best Practice and Testing the Functional Code, explains the best practice in the functional approach, including the creation of an honest signature and dealing with the side-effects. We also separate the code into domain logic and mutable shell and then test it using unit testing. 

    What you need for this book

    To walk through this book and successfully compile all the source code, we require a personal computer that runs Microsoft Windows 10 (or higher) with Visual Studio Community 2015 Update 3 installed for the running of code in chapters 1-8, 10, 11 and Visual Studio Community 2017 RC (Release Candidate) installed for the running of code in chapter 9. We also need the .NET Framework 4.6.2 unless you need to recode all the source code to run in your current version of .NET Framework. You also need .NET Core 1.0 if you want to compile all code in another platform since all code are compatible with .NET Core 1.0.

    Who this book is for

    This book is suitable for C# developers with basic prior knowledge of C# and with no functional programming experience at all.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: We can include other contexts through the use of the include directive.

    A block of code is set as follows:

    namespace ActionFuncDelegates

    {

      public partial class Program

      {

        static void Main(string[] args)

        {

          //ActionDelegateInvoke();

          FuncDelegateInvoke();

        }

      }

    When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    Console.WriteLine(Prime Number from 0 - 49 are:); foreach (int i in extractedData) Console.Write({0} \t, i)

    ;

    Console.WriteLine();

    Any command-line input or output is written as follows:

    C:\>dir | more

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: We have a Body property containing {(a * b)}, NodeType containing Lambda, Type containing the Func delegate with three templates.

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Functional-CSharp. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at copyright@packtpub.com with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at questions@packtpub.com, and we will do our best to address the problem.

    Chapter 1. Tasting Functional Style in C#

    Functional programming is a style of constructing the elements and structure of computer program which treats computations like evaluations in mathematical functions. Although there are some specifically designed languages for creating functional programming, such as Haskell or Scala, we can also use C# to accomplish designing functional programming.

    In the first chapter of this book, we are going to explore the functional programming by testing it. We will use the power of C# to construct some functional code. We will also deal with the features in C# that are mostly used in developing functional programs. By the end of this chapter, we will have an idea of what the functional approach in C# will be like. Here are the topics we will cover in this chapter:

    Introduction to functional programming concepts

    Comparison between the functional and imperative approach

    The concepts of functional programming

    Using the mathematical approach to understand functional programming

    Refactoring imperative code to functional code

    The advantages and disadvantages of functional programming

    Introducing functional programming

    In functional programming, we write functions without side effects the way we write in Mathematics. The variable in the code function represents the value of the function parameter, and it similar to the mathematical function. The idea is that a programmer defines the functions that contain the expression, definition, and the parameters that can be expressed by a variable in order to solve problems.

    After a programmer builds the function and sends the function to the computer, it's the computer's turn to do its job. In general, the role of the computer is to evaluate the expression in the function and return the result. We can imagine that the computer acts like a calculator since it will analyze the expression from the function and yield the result to the user in a printed format. The calculator will evaluate a function which are composed of variables passed as parameters and expressions which form the body of the function. Variables are substituted by their values in the expression. We can give simple expression and compound expressions using algebraic operators. Since expressions without assignments never alter the value, sub expressions needs to be evaluated only once.

    Suppose we have the expression 3 + 5 inside a function. The computer will definitely return 8 as the result right after it completely evaluates it. However, this is just a simple example of how the computer acts in evaluating an expression. In fact, a programmer can increase the ability of the computer by creating a complex definition and expression inside the function. Not only can the computer evaluate the simple expression, but it can also evaluate the complex calculation and expression.

    Understanding definitions, scripts, and sessions

    As we discussed earlier about a calculator that will analyze the expression from the function, let's imagine we have a calculator that has a console panel like a computer does. The difference between that and a conventional calculator is that we have to press Enter instead of = (equal to) in order to run the evaluation process of the expression. Here, we can type the expression and then press Enter . Now, imagine that we type the following expression:

    3 x 9

    Immediately after pressing Enter , the computer will print 27 in the console, and that's what we are expecting. The computer has done a great job of evaluating the expression we gave. Now, let's move to analyzing the following definitions. Imagine that we type them on our functional calculator:

    square a = a * a

    max a b  = a, if a >= b

            = b, if b > a

    We have defined the two definitions, square and max. We can call the list of definitions script. By calling the square function followed by any number representing variable a, we will be given the square of that number. Also, in the max definition, we serve two numbers to represent variables a and b, and then the computer will evaluate this expression to find out the biggest number between the variables.

    By defining these two definitions, we can use them as a function, which we can call session, as follows:

    square (1 + 2)

    The computer will definitely print 9 after evaluating the preceding function. The computer will also be able to evaluate the following function:

    max 1 2

    It will return 2 as the result based on the definition we defined earlier. This is also possible if we provide the following expression:

    square (max 2 5)

    Then, 25 will be displayed in our calculator console panel.

    We can also modify a definition using the previous definition. Suppose we want to quadruple an integer number and take advantage of the definition of the square function; here is what we can send to our calculator:

    quad q = square q * square q

    quad 10

    The first line of the preceding expression is a definition of the quad function. In

    Enjoying the preview?
    Page 1 of 1