SlideShare una empresa de Scribd logo
1 de 55
Functional
Programming
Objective
The popularity of functional programming has been increasing lately.
Specially pure functional languages like F#, Haskell, Scala, Erlang and Elixir are becoming more
popular.
Even OOP languages like C# and Java have included some functional libraries
Ex: LINQ and lambda functions
This session will focus on what Functional Programming is, how it is implemented and why it has
become popular.
Content
Programming Paradigms
Imperative vs. Declarative Programming
Functional Programming
Benefits of Functional Programming
Main Concepts
◦ Pure functions
◦ Immutability
◦ Higher Order Functions
◦ Referential Transparency
Implementing functional programming with C#
Multi-paradigm approach
Popularity of Functional Programming
Programming
Paradigms
A programming paradigm is a way of
programming
It is a style of approaching a programming
problem.
Types
◦ Imperative
◦ Declarative
Imperative Programming
Focus on 'How' something needs to be done
Explicitly declares sequence of steps to be followed that changes the state
Types
◦ Procedural
◦ Object Oriented Programming
Example:
Declarative Programming
Focuses on 'What' the result should be
Expresses the logic of the program without explicitly declaring the steps
Types
◦ Functional Programming
◦ Logic Programming
◦ Database approach
Example:
Issues in Imperative Programming
Less support
for
Concurrency
Vulnerable to
'Race
Conditions'
Functional Programming
is one way to address
these issues effectively
What is
Functional
Programming?
"In computer science, functional programming is a
programming paradigm—a style of building the structure
and elements of computer programs—that treats
computation as the evaluation of mathematical functions
and avoids changing-state and mutable data."
-Wikipedia
/
Functional Programming
Treats functions
as First Class
values
Avoid state
mutations
First Class
Values
Treat functions as values
Pass functions as data
• Be refered from constants and variables
• Be passed as a parameter to another function
• Be returned as a result from another function
Functions as First-Class Entities can:
Avoiding State
Mutation
Avoid destructive updates The value stored prior to the
update should not be destroyed
Why Functional Programming?
LESS BUGS SUPPORT FOR PARALLEL
PROGRAMMING (THREAD SAFE)
EFFICIENCY
Other Benefits
INCREASED
READABILITY
INCREASED
UNDERSTANDABILITY
EASIER FOR TESTING
AND DEBUGGING
Main Concepts
PURE
FUNCTIONS
RECURSION REFERENTIAL
TRANSPARENCY
HIGHER ORDER
FUNCTIONS
IMMUTABLE
VARIABLES
Pure Functions
A pure function:
◦ Returns the same result if given the same
arguments
◦ Causes no observable side effects
Returning same result for same arguments
The value of the variable on the
global context has changed
Ex: Functions that read
files or generate
random numbers can
never be pure
No Side Effects
Side Effect :
◦ An interaction with an external mutable state apart from the function's input and output
A side effect can be :
◦ Mutation of a global scope
◦ Mutation of the input arguments of a function
◦ Throwing exceptions
◦ Performing any I/O operation
Function Honesty
A concept similar to pure functions
The function is an 'honest' representation of its method signature
The behavior can be predicted using the signature.
Recursion
Recursion is when a function
calls itself repeatedly.
Used to remove local side
effects
Specially in loops and similar
iterative structures
Example: Sum of integers from 1 -10
Non-recursive method Recursive method
Interacts with external
variable result.
Referential
Transparency
Being able to replace a
function with its result.
Supported by Pure Functions
and Immutable Variables
◦ Pure functions give the
same result for the same
arguments
Higher Order Functions
Functions that:
◦ Take one or more functions as arguments
AND/OR
◦ Returns a function as a result
Immutable Variables
Variables and objects
that once created do
not change
Always maintain the
same state
Thread safe Readability increases
Example
Creating a mutable object
Example
Creating an immutable object
Functional Programming with C#
C# mainly uses an imperative programming approach
(It's basically an OOP language)
But it also has some declarative approaches
Ex: LINQ library, lambda functions
FP Vs. OOP
Functional Programming​ OOP​
Use Immutable data​ Use Mutable data​
Declarative programming​ Imperative programming​
Support parallel programming​ Less suitable for parallel programming​
No side-effects​ Can produce side-effects​
Flow control using function calls and recursion​ Flow control using loops and conditional statements​
Iterate collection data using recursion​ Iterate collection data using loop​
Execution order of statements is less important​ Execution order of statements is important​
Implementing Functional
Programming with C#
LINQ
LINQ is a functional library
Follows declarative approach for common operations on
sequences (list)
Ex: Map
Filter
Sort
LINQ -Map
Getting a new sequence from a given sequence where the elements of the new sequence have
been obtained by subjecting to a function
Example:
LINQ - Filter
Getting a new sequence from an old sequence where the elements of the new sequence are
those that pass a certain condition (predicate)
Example:
LINQ - Sort
Getting a new sequence by ordering the old sequence according to the key provided in a key
selector function.
Example:
Method chaining
Method chaining is a way of calling a method directly onto the result of a previous method.
We do this all the time with LINQ.
It is a functional approach because it avoids temporary variables and state changes.
Fluent Interfaces
Fluent interfaces are an implementation of method chaining.
It is a more complex version of the simple method chaining.
The main feature of fluent interfaces over method chaining is that it is self referencing.
Not all implementations of method chaining will be a fluent interface
The Where and OrderBy functions act on the same instance
of the IEnumerable returned from the Select function.
Function Honesty
An honest function is a function that does exactly what it says in the function signature.
No unexpected outputs or inputs.
The exception is not an
output predicted by the
function signature.
Then this is a dishonest
function
This method signature says that this function will definitely return an integer.
But actually the truth is this function might return an integer.
It can also throw an exception.
Functional Error Handling
Imperative approach
◦ throw/try/catch -> Side effects
Declarative approach
◦ Treat the error as part of the payload
Approaches:
◦ Implementation of Option or Either types
Is C# a pure functional
language?
The answer is both YES and NO.
NO because C# is mainly a OOP language and follows
imperative style
YES because C# has some support for functional
concepts like with LINQ
C# is a Multi-Paradigm language
Multi-Paradigm Approach
Actually the multi-paradigm approach is a lot more practical when considering
large programs rather than the pure functional approach. It's very difficult to
apply functional approaches to an entire program
Ex: I/O operations are considered side effects that need to be avoided in FP. But
in a real world application it is impossible to not have I/O operations at all.
So, the solution is to isolate the I/O operations to be performed imperatively and
have everything else follow a functional approach
INPUT OPERATION
SOME OTHER
OPERATIONS OUTPUT OPERATION
Do this
functionally. There
can be no side
effect causing
functions here
These should be
isolated. You can
use an imperative
approach here
Example:
Multi-paradigm approach can
also help avoid some of the
other issues in pure functional
programming
Problems with pure functional programming
LEARNING CURVE DIFFICULT TO WRITE COMPLETE
PROGRAMS IMPLEMENTING
ONLY FUNCTIONAL
PROGRAMMING
HIGH MEMORY CONSUMPTION NEED TO WRITE EXTRA CODE
Why is FP
trending right
now?
Pure functional languages like F#, Haskell, Erlang and Elixir are
becoming more popular recently.
This is mainly because of the greater support for concurrency and
parallel processing.
A lot of other traditionally non-functional languages and
frameworks have also introduced different functional utility
libraries to support functional programming.
Ex: RxJs, lazy.js, immutable.js and rambda
Success Stories
WhatsApp supports 900 million users with only 50 Engineers using
Erlang
Discord handles over a million requests per minute using Elixir
Facebook's anti-spam system uses Haskell
For each system the most important aspects were concurrency and speed.
They were able to achieve it using functional programming
Recap
There are 2 main programming paradigms, Imperative and Declarative
Functional programming is a declarative approach that avoids state changes and mutable data
The main concepts are Pure functions, recursion, higher order functions, immutability and
referential transparency.
C# is a multi-paradigm language that has support for functional programming approaches.
Ex: LINQ library
The main problem with Functional Programming is that it is difficult to implement to a whole
program.
But it is more popular now because of greater support and suitability for parallel processing
Resources
Functional Programming in C# by Enrico Buonanno
.NET documentation
THANK YOU!
Questions?

Más contenido relacionado

La actualidad más candente

Learning programming
Learning programmingLearning programming
Learning programming
TuanDanaIm
 
Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloud
lennartkats
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
Terry Yoast
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
Stratio
 
9781439035665 ppt ch02
9781439035665 ppt ch029781439035665 ppt ch02
9781439035665 ppt ch02
Terry Yoast
 

La actualidad más candente (20)

Learning programming
Learning programmingLearning programming
Learning programming
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
C aptitude book
C aptitude bookC aptitude book
C aptitude book
 
Language Engineering in the Cloud
Language Engineering in the CloudLanguage Engineering in the Cloud
Language Engineering in the Cloud
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
 
C programming for Computing Techniques
C programming for Computing TechniquesC programming for Computing Techniques
C programming for Computing Techniques
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Programming Paradigm & Languages
Programming Paradigm & LanguagesProgramming Paradigm & Languages
Programming Paradigm & Languages
 
Functional programming in scala
Functional programming in scalaFunctional programming in scala
Functional programming in scala
 
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
[4DEV] Bartosz Sokół - Functional developer in object oriented world - how F#...
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...
 
Introduction to programming by MUFIX Commnity
Introduction to programming by MUFIX CommnityIntroduction to programming by MUFIX Commnity
Introduction to programming by MUFIX Commnity
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutions
 
Tech for devs, F#
Tech for devs, F#Tech for devs, F#
Tech for devs, F#
 
Compilers in computer programming
Compilers in computer programmingCompilers in computer programming
Compilers in computer programming
 
05 functional programming
05 functional programming05 functional programming
05 functional programming
 
9781439035665 ppt ch02
9781439035665 ppt ch029781439035665 ppt ch02
9781439035665 ppt ch02
 
Code Generation in Perl
Code Generation in PerlCode Generation in Perl
Code Generation in Perl
 
Programming Methodology
Programming MethodologyProgramming Methodology
Programming Methodology
 
Functional Programming - Worth the Effort
Functional Programming - Worth the EffortFunctional Programming - Worth the Effort
Functional Programming - Worth the Effort
 

Similar a Functional programming

C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
techfreak
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
JEEVANANTHAMG6
 

Similar a Functional programming (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)Functional Programming for OO Programmers (part 1)
Functional Programming for OO Programmers (part 1)
 
Oop.pptx
Oop.pptxOop.pptx
Oop.pptx
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Prgramming paradigms
Prgramming paradigmsPrgramming paradigms
Prgramming paradigms
 
Functional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNextFunctional Programming in JavaScript & ESNext
Functional Programming in JavaScript & ESNext
 
Introduction to functional programming
Introduction to functional programmingIntroduction to functional programming
Introduction to functional programming
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
Functional programming is the most extreme programming
Functional programming is the most extreme programmingFunctional programming is the most extreme programming
Functional programming is the most extreme programming
 
C++ question and answers
C++ question and answersC++ question and answers
C++ question and answers
 
Domain Modeling & Full-Stack Web Development F#
Domain Modeling & Full-Stack Web Development F#Domain Modeling & Full-Stack Web Development F#
Domain Modeling & Full-Stack Web Development F#
 
PARADIGM IT.pptx
PARADIGM IT.pptxPARADIGM IT.pptx
PARADIGM IT.pptx
 
Presentation
PresentationPresentation
Presentation
 
Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
Porting the NetBeans Java 8 Enhanced For Loop Lambda Expression Refactoring t...
 
Oop in c++ lecture 1
Oop in c++  lecture 1Oop in c++  lecture 1
Oop in c++ lecture 1
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Functional programming in TypeScript
Functional programming in TypeScriptFunctional programming in TypeScript
Functional programming in TypeScript
 

Último

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Functional programming

  • 2. Objective The popularity of functional programming has been increasing lately. Specially pure functional languages like F#, Haskell, Scala, Erlang and Elixir are becoming more popular. Even OOP languages like C# and Java have included some functional libraries Ex: LINQ and lambda functions This session will focus on what Functional Programming is, how it is implemented and why it has become popular.
  • 3. Content Programming Paradigms Imperative vs. Declarative Programming Functional Programming Benefits of Functional Programming Main Concepts ◦ Pure functions ◦ Immutability ◦ Higher Order Functions ◦ Referential Transparency Implementing functional programming with C# Multi-paradigm approach Popularity of Functional Programming
  • 4. Programming Paradigms A programming paradigm is a way of programming It is a style of approaching a programming problem. Types ◦ Imperative ◦ Declarative
  • 5. Imperative Programming Focus on 'How' something needs to be done Explicitly declares sequence of steps to be followed that changes the state Types ◦ Procedural ◦ Object Oriented Programming
  • 7. Declarative Programming Focuses on 'What' the result should be Expresses the logic of the program without explicitly declaring the steps Types ◦ Functional Programming ◦ Logic Programming ◦ Database approach
  • 9. Issues in Imperative Programming Less support for Concurrency Vulnerable to 'Race Conditions'
  • 10. Functional Programming is one way to address these issues effectively
  • 11. What is Functional Programming? "In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data." -Wikipedia
  • 12. / Functional Programming Treats functions as First Class values Avoid state mutations
  • 13. First Class Values Treat functions as values Pass functions as data • Be refered from constants and variables • Be passed as a parameter to another function • Be returned as a result from another function Functions as First-Class Entities can:
  • 14. Avoiding State Mutation Avoid destructive updates The value stored prior to the update should not be destroyed
  • 15. Why Functional Programming? LESS BUGS SUPPORT FOR PARALLEL PROGRAMMING (THREAD SAFE) EFFICIENCY
  • 18. Pure Functions A pure function: ◦ Returns the same result if given the same arguments ◦ Causes no observable side effects
  • 19. Returning same result for same arguments The value of the variable on the global context has changed
  • 20. Ex: Functions that read files or generate random numbers can never be pure
  • 21. No Side Effects Side Effect : ◦ An interaction with an external mutable state apart from the function's input and output A side effect can be : ◦ Mutation of a global scope ◦ Mutation of the input arguments of a function ◦ Throwing exceptions ◦ Performing any I/O operation
  • 22.
  • 23.
  • 24. Function Honesty A concept similar to pure functions The function is an 'honest' representation of its method signature The behavior can be predicted using the signature.
  • 25. Recursion Recursion is when a function calls itself repeatedly. Used to remove local side effects Specially in loops and similar iterative structures
  • 26. Example: Sum of integers from 1 -10 Non-recursive method Recursive method Interacts with external variable result.
  • 27. Referential Transparency Being able to replace a function with its result. Supported by Pure Functions and Immutable Variables ◦ Pure functions give the same result for the same arguments
  • 28. Higher Order Functions Functions that: ◦ Take one or more functions as arguments AND/OR ◦ Returns a function as a result
  • 29.
  • 30. Immutable Variables Variables and objects that once created do not change Always maintain the same state Thread safe Readability increases
  • 33. Functional Programming with C# C# mainly uses an imperative programming approach (It's basically an OOP language) But it also has some declarative approaches Ex: LINQ library, lambda functions
  • 34. FP Vs. OOP Functional Programming​ OOP​ Use Immutable data​ Use Mutable data​ Declarative programming​ Imperative programming​ Support parallel programming​ Less suitable for parallel programming​ No side-effects​ Can produce side-effects​ Flow control using function calls and recursion​ Flow control using loops and conditional statements​ Iterate collection data using recursion​ Iterate collection data using loop​ Execution order of statements is less important​ Execution order of statements is important​
  • 36. LINQ LINQ is a functional library Follows declarative approach for common operations on sequences (list) Ex: Map Filter Sort
  • 37. LINQ -Map Getting a new sequence from a given sequence where the elements of the new sequence have been obtained by subjecting to a function Example:
  • 38. LINQ - Filter Getting a new sequence from an old sequence where the elements of the new sequence are those that pass a certain condition (predicate) Example:
  • 39. LINQ - Sort Getting a new sequence by ordering the old sequence according to the key provided in a key selector function. Example:
  • 40. Method chaining Method chaining is a way of calling a method directly onto the result of a previous method. We do this all the time with LINQ. It is a functional approach because it avoids temporary variables and state changes.
  • 41. Fluent Interfaces Fluent interfaces are an implementation of method chaining. It is a more complex version of the simple method chaining. The main feature of fluent interfaces over method chaining is that it is self referencing. Not all implementations of method chaining will be a fluent interface The Where and OrderBy functions act on the same instance of the IEnumerable returned from the Select function.
  • 42. Function Honesty An honest function is a function that does exactly what it says in the function signature. No unexpected outputs or inputs. The exception is not an output predicted by the function signature. Then this is a dishonest function
  • 43. This method signature says that this function will definitely return an integer. But actually the truth is this function might return an integer. It can also throw an exception.
  • 44. Functional Error Handling Imperative approach ◦ throw/try/catch -> Side effects Declarative approach ◦ Treat the error as part of the payload Approaches: ◦ Implementation of Option or Either types
  • 45. Is C# a pure functional language? The answer is both YES and NO. NO because C# is mainly a OOP language and follows imperative style YES because C# has some support for functional concepts like with LINQ C# is a Multi-Paradigm language
  • 46. Multi-Paradigm Approach Actually the multi-paradigm approach is a lot more practical when considering large programs rather than the pure functional approach. It's very difficult to apply functional approaches to an entire program Ex: I/O operations are considered side effects that need to be avoided in FP. But in a real world application it is impossible to not have I/O operations at all. So, the solution is to isolate the I/O operations to be performed imperatively and have everything else follow a functional approach
  • 47. INPUT OPERATION SOME OTHER OPERATIONS OUTPUT OPERATION Do this functionally. There can be no side effect causing functions here These should be isolated. You can use an imperative approach here Example:
  • 48. Multi-paradigm approach can also help avoid some of the other issues in pure functional programming
  • 49. Problems with pure functional programming LEARNING CURVE DIFFICULT TO WRITE COMPLETE PROGRAMS IMPLEMENTING ONLY FUNCTIONAL PROGRAMMING HIGH MEMORY CONSUMPTION NEED TO WRITE EXTRA CODE
  • 50. Why is FP trending right now? Pure functional languages like F#, Haskell, Erlang and Elixir are becoming more popular recently. This is mainly because of the greater support for concurrency and parallel processing. A lot of other traditionally non-functional languages and frameworks have also introduced different functional utility libraries to support functional programming. Ex: RxJs, lazy.js, immutable.js and rambda
  • 51. Success Stories WhatsApp supports 900 million users with only 50 Engineers using Erlang Discord handles over a million requests per minute using Elixir Facebook's anti-spam system uses Haskell For each system the most important aspects were concurrency and speed. They were able to achieve it using functional programming
  • 52. Recap There are 2 main programming paradigms, Imperative and Declarative Functional programming is a declarative approach that avoids state changes and mutable data The main concepts are Pure functions, recursion, higher order functions, immutability and referential transparency. C# is a multi-paradigm language that has support for functional programming approaches. Ex: LINQ library The main problem with Functional Programming is that it is difficult to implement to a whole program. But it is more popular now because of greater support and suitability for parallel processing
  • 53. Resources Functional Programming in C# by Enrico Buonanno .NET documentation

Notas del editor

  1. Crop