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?

Functional programming

  • 1.
  • 2.
    Objective The popularity offunctional 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 paradigmis 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
  • 6.
  • 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
  • 8.
  • 9.
    Issues in ImperativeProgramming Less support for Concurrency Vulnerable to 'Race Conditions'
  • 10.
    Functional Programming is oneway to address these issues effectively
  • 11.
    What is Functional Programming? "In computerscience, 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 asFirst Class values Avoid state mutations
  • 13.
    First Class Values Treat functionsas 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 destructiveupdates The value stored prior to the update should not be destroyed
  • 15.
    Why Functional Programming? LESSBUGS SUPPORT FOR PARALLEL PROGRAMMING (THREAD SAFE) EFFICIENCY
  • 16.
  • 17.
  • 18.
    Pure Functions A purefunction: ◦ Returns the same result if given the same arguments ◦ Causes no observable side effects
  • 19.
    Returning same resultfor same arguments The value of the variable on the global context has changed
  • 20.
    Ex: Functions thatread files or generate random numbers can never be pure
  • 21.
    No Side Effects SideEffect : ◦ 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
  • 24.
    Function Honesty A conceptsimilar 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 whena function calls itself repeatedly. Used to remove local side effects Specially in loops and similar iterative structures
  • 26.
    Example: Sum ofintegers from 1 -10 Non-recursive method Recursive method Interacts with external variable result.
  • 27.
    Referential Transparency Being able toreplace 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 Functionsthat: ◦ Take one or more functions as arguments AND/OR ◦ Returns a function as a result
  • 30.
    Immutable Variables Variables andobjects that once created do not change Always maintain the same state Thread safe Readability increases
  • 31.
  • 32.
  • 33.
    Functional Programming withC# 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 FunctionalProgramming​ 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​
  • 35.
  • 36.
    LINQ LINQ is afunctional library Follows declarative approach for common operations on sequences (list) Ex: Map Filter Sort
  • 37.
    LINQ -Map Getting anew sequence from a given sequence where the elements of the new sequence have been obtained by subjecting to a function Example:
  • 38.
    LINQ - Filter Gettinga 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 Gettinga new sequence by ordering the old sequence according to the key provided in a key selector function. Example:
  • 40.
    Method chaining Method chainingis 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 interfacesare 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 honestfunction 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 signaturesays 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 Imperativeapproach ◦ 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# apure 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 themulti-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 OPERATIONSOUTPUT 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 alsohelp avoid some of the other issues in pure functional programming
  • 49.
    Problems with purefunctional programming LEARNING CURVE DIFFICULT TO WRITE COMPLETE PROGRAMS IMPLEMENTING ONLY FUNCTIONAL PROGRAMMING HIGH MEMORY CONSUMPTION NEED TO WRITE EXTRA CODE
  • 50.
    Why is FP trendingright 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 supports900 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 2main 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 inC# by Enrico Buonanno .NET documentation
  • 54.
  • 55.

Editor's Notes