SlideShare a Scribd company logo
Functional Programming 101
Agenda
What is FP
Basics of FP
Pure Functions
Immutability
Referential Transparency
Higher Order Functions
Partial Application and Currying
What is FP ?
In functional programming, we place a major emphasis on
writing code using functions as building blocks. Your program is
defined in terms of one main function. This main function is
defined in terms of other functions, which are in turn defined in
terms of still more functions, until at the bottom level the
functions are just language primitives like number or string.
What is FP ?
Basics
Every Software program has two things
● Behavior(What the program does)
● Data
In FP , behavior is handled only using functions and data is
immutable. Rather than changing data they take in, functions in
functional programming take in data as input and produce new
values as output(always). Also functions in FP can be passed
around just like data.
Basics
Functions
● Functions are pure
● Functions use immutable data
● Functions guarantee referential transparency
● Functions are first-class entities
Pure Functions
Qualities of Pure Functions
● The function depends only on the input provided to it to
produce a result (and not on any external state).
● The function does not cause any observable side effects,
such as modifying a global object or modifying a parameter
passed by reference
Pure Functions
var PI = 3.14;
const calculateArea = (radius) => radius * radius * PI;
let count = 1;
const increment = (val) => count = count + val;
const reverseArray = (array) => array.reverse();
Pure Functions
async function amountExceedsCreditLimit(amount) {
const limit = await getCreditLimit() // assume api call
if (amount > limit) {
return true;
}
return false;
}
console.log(“Hello World!”);
Pure Functions benefits
● Pure functions are predictable
● Pure functions are easy to test
● Easier to refactor
Immutability
var firstName = “Maneesh”
firstName[3] = “i”;
console.log(firstName[3]);
console.log(firstName);
firstName = firstName.slice(0,3);
console.log(firstName);
Immutability
Mutation modifies the underlying object without affecting the
link between the variable and the object, whereas assignment
changes the link to a different object, but doesn’t modify any
objects.
Functions -Referential
Transparency
Functions -Referential
Transparency
If a function consistently yields the same result for the same
input , it is referentially transparent. Referential transparency
gives the ability to freely replace an expression with its value
and not change the behavior of the program.
Functions -Referential
Transparency
Pure functions + immutable data = referential transparency
i.e a function that doesn't rely on external states or mutable
data will always return the same output for a given input.
Functions are first class Citizens
● Refer to it from constants and variables
● Pass it as a parameter to other functions
● Return it as result from other functions
A higher order function is a function that meets at least one of
the following requirements: Note most functions which take a
callback are higher order functions.
● It accepts a function as an argument
● It returns a new function
Higher Order Functions
Benefits of higher order functions
● Hide Implementation Details
numbers.stream().map(s -> Integer.valueOf(s))
.filter(number -> number % 2 == 0)
.collect(Collectors.toList());
Higher Order Functions
Benefits of higher order functions
● Adding Functionality to an Existing Function
function logResult(fn) {
return (...args) => { const result = fn(...args)
console.log(result)
return result
}}
Higher Order Functions
const findAndMultiply = (index,multiplier) => {
return (array) => {
if (array && typeof(array[index] == ‘number’) {
return array[index] * multiplier ;
else{
Return “Bhaiya, ye na ho pai”’
}
};
};
Higher Order Functions
Function Composition
Create small reusable functions that you can combine to
compose new functions.
BiFunction<String, List<Article>, List<Article>> byAuthor =
(name, articles) -> articles.stream()
.filter(a -> a.getAuthor().equals(name))
.collect(Collectors.toList());
Function Composition
BiFunction<String, List<Article>, List<Article>> byTag =
(tag, articles) -> articles.stream()
.filter(a -> a.getTags().contains(tag))
.collect(Collectors.toList());
Function<List<Article>, List<Article>> sortByDate =
articles -> articles.stream()
.sorted((x, y) -> y.published().compareTo(x.published()))
.collect(Collectors.toList());
Function Composition
Function<List<Article>, Optional<Article>> first =
a -> a.stream().findFirst();
Function<List<Article>, Optional<Article>> newest =
first.compose(sortByDate);
BiFunction<String, List<Article>, List<Article>>
byAuthorSorted = byAuthor.andThen(sortByDate);
Function Composition
The compose method uses a parameter named, before, and the
andThen method uses a parameter named, after. These names
indicate the order that the functions will be evaluated on.
f(x) = (2+x)*3
g(x) = 2 +(x*3)
Use compose and andThen to form f(x) and g(x).
Function Composition
Function<Integer, Integer> baseFunction = t -> t + 2;
Function<Integer, Integer> afterFunction =
baseFunction.andThen(t -> t * 3);
System.out.println(afterFunction.apply(5));
Function<Integer, Integer> beforeFunction =
baseFunction.compose(t -> t * 3);
System.out.println(beforeFunction.apply(5));
when the apply method is executed, the corresponding lambda
expression is executed
Function Composition
int hoursWorked[] = {8, 12, 8, 6, 6, 5, 6, 0};
int totalHoursWorked = Arrays.stream(hoursWorked)
.filter(n -> n > 6)
.sum();
LocalDateTime timeInstance = LocalDateTime.now()
.plusDays(3)
.minusHours(4)
.plusWeeks(1)
.plusYears(2);
Fluent Interfaces
Partial application is a way to turn a function that expects
multiple parameters into one that will keep returning a new
function until it receives all its arguments
const f = (a,b,c) => a * b *c
const g = partial(f,[2,3])
const h = g(4)
Partial Application
const applyTax = (amount,tax) => amount + (amount * tax)
applyTax(0.08) =>
applyTaxOfEightPercent = partial(applyTax,[0.08]);
applyTaxOfFivePercent = partial(applyTax,[0.05]);
applyTaxofEightPercent(100);
applyTaxofFivePercent(100);
Exercise - Template design pattern. Try implementing it using
partial application.
Partial Application
Currying is the process of taking a function that accepts N
arguments and turning it into a chained series of N functions
that each take one argument. The difference between partial
application and currying is that with currying, you can never
provide more than one argument — it has to be either one or
zero. If a function takes 5 arguments, we can partially apply 3 of
them. But with currying, we only pass one argument at a time.
So if a function takes 5 arguments, we have to curry 5 times
before we get the resulting value.
Future and Promise are an application of currying.
Currying
Ad

More Related Content

What's hot (19)

FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Function C++
Function C++ Function C++
Function C++
Shahzad Afridi
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
Vishalini Mugunen
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Sachin Sharma
 
PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMS
Arpee Callejo
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
Will Livengood
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMS
Arpee Callejo
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
Vraj Patel
 

Similar to Functional programming 101 (20)

From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
Function
Function Function
Function
Kathmandu University
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
Sampath Kumar
 
Functional Programming with Javascript
Functional Programming with JavascriptFunctional Programming with Javascript
Functional Programming with Javascript
Deepankar Chopra
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Lecture 11 - Functions
Lecture 11 - FunctionsLecture 11 - Functions
Lecture 11 - Functions
Md. Imran Hossain Showrov
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
Functions
FunctionsFunctions
Functions
Pragnavi Erva
 
Functional programming
Functional programmingFunctional programming
Functional programming
S M Asaduzzaman
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
Sartaj Singh
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
estorebackupr
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
Function
FunctionFunction
Function
Sukhdarshan Singh
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
Olexandra Dmytrenko
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Mario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
Codemotion
 
Functional Programming with Javascript
Functional Programming with JavascriptFunctional Programming with Javascript
Functional Programming with Javascript
Deepankar Chopra
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++Generalized Functors - Realizing Command Design Pattern in C++
Generalized Functors - Realizing Command Design Pattern in C++
ppd1961
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
Sartaj Singh
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
estorebackupr
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
Adam Getchell
 
Basic information of function in cpu
Basic information of function in cpuBasic information of function in cpu
Basic information of function in cpu
Dhaval Jalalpara
 
6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming6. Functions in C ++ programming object oriented programming
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Ad

Recently uploaded (20)

Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& ConsiderationsDesigning AI-Powered APIs on Azure: Best Practices& Considerations
Designing AI-Powered APIs on Azure: Best Practices& Considerations
Dinusha Kumarasiri
 
Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)Who Watches the Watchmen (SciFiDevCon 2025)
Who Watches the Watchmen (SciFiDevCon 2025)
Allon Mureinik
 
Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025Avast Premium Security Crack FREE Latest Version 2025
Avast Premium Security Crack FREE Latest Version 2025
mu394968
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
F-Secure Freedome VPN 2025 Crack Plus Activation  New VersionF-Secure Freedome VPN 2025 Crack Plus Activation  New Version
F-Secure Freedome VPN 2025 Crack Plus Activation New Version
saimabibi60507
 
The Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdfThe Significance of Hardware in Information Systems.pdf
The Significance of Hardware in Information Systems.pdf
drewplanas10
 
Not So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java WebinarNot So Common Memory Leaks in Java Webinar
Not So Common Memory Leaks in Java Webinar
Tier1 app
 
Adobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest VersionAdobe Illustrator Crack FREE Download 2025 Latest Version
Adobe Illustrator Crack FREE Download 2025 Latest Version
kashifyounis067
 
Expand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchangeExpand your AI adoption with AgentExchange
Expand your AI adoption with AgentExchange
Fexle Services Pvt. Ltd.
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025Adobe Lightroom Classic Crack FREE Latest link 2025
Adobe Lightroom Classic Crack FREE Latest link 2025
kashifyounis067
 
Solidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license codeSolidworks Crack 2025 latest new + license code
Solidworks Crack 2025 latest new + license code
aneelaramzan63
 
Revolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptxRevolutionizing Residential Wi-Fi PPT.pptx
Revolutionizing Residential Wi-Fi PPT.pptx
nidhisingh691197
 
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Proactive Vulnerability Detection in Source Code Using Graph Neural Networks:...
Ranjan Baisak
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Requirements in Engineering AI- Enabled Systems: Open Problems and Safe AI Sy...
Lionel Briand
 
Ad

Functional programming 101

  • 2. Agenda What is FP Basics of FP Pure Functions Immutability Referential Transparency Higher Order Functions Partial Application and Currying
  • 3. What is FP ? In functional programming, we place a major emphasis on writing code using functions as building blocks. Your program is defined in terms of one main function. This main function is defined in terms of other functions, which are in turn defined in terms of still more functions, until at the bottom level the functions are just language primitives like number or string.
  • 5. Basics Every Software program has two things ● Behavior(What the program does) ● Data In FP , behavior is handled only using functions and data is immutable. Rather than changing data they take in, functions in functional programming take in data as input and produce new values as output(always). Also functions in FP can be passed around just like data.
  • 7. Functions ● Functions are pure ● Functions use immutable data ● Functions guarantee referential transparency ● Functions are first-class entities
  • 8. Pure Functions Qualities of Pure Functions ● The function depends only on the input provided to it to produce a result (and not on any external state). ● The function does not cause any observable side effects, such as modifying a global object or modifying a parameter passed by reference
  • 9. Pure Functions var PI = 3.14; const calculateArea = (radius) => radius * radius * PI; let count = 1; const increment = (val) => count = count + val; const reverseArray = (array) => array.reverse();
  • 10. Pure Functions async function amountExceedsCreditLimit(amount) { const limit = await getCreditLimit() // assume api call if (amount > limit) { return true; } return false; } console.log(“Hello World!”);
  • 11. Pure Functions benefits ● Pure functions are predictable ● Pure functions are easy to test ● Easier to refactor
  • 12. Immutability var firstName = “Maneesh” firstName[3] = “i”; console.log(firstName[3]); console.log(firstName); firstName = firstName.slice(0,3); console.log(firstName);
  • 13. Immutability Mutation modifies the underlying object without affecting the link between the variable and the object, whereas assignment changes the link to a different object, but doesn’t modify any objects.
  • 15. Functions -Referential Transparency If a function consistently yields the same result for the same input , it is referentially transparent. Referential transparency gives the ability to freely replace an expression with its value and not change the behavior of the program.
  • 16. Functions -Referential Transparency Pure functions + immutable data = referential transparency i.e a function that doesn't rely on external states or mutable data will always return the same output for a given input.
  • 17. Functions are first class Citizens ● Refer to it from constants and variables ● Pass it as a parameter to other functions ● Return it as result from other functions
  • 18. A higher order function is a function that meets at least one of the following requirements: Note most functions which take a callback are higher order functions. ● It accepts a function as an argument ● It returns a new function Higher Order Functions
  • 19. Benefits of higher order functions ● Hide Implementation Details numbers.stream().map(s -> Integer.valueOf(s)) .filter(number -> number % 2 == 0) .collect(Collectors.toList()); Higher Order Functions
  • 20. Benefits of higher order functions ● Adding Functionality to an Existing Function function logResult(fn) { return (...args) => { const result = fn(...args) console.log(result) return result }} Higher Order Functions
  • 21. const findAndMultiply = (index,multiplier) => { return (array) => { if (array && typeof(array[index] == ‘number’) { return array[index] * multiplier ; else{ Return “Bhaiya, ye na ho pai”’ } }; }; Higher Order Functions
  • 23. Create small reusable functions that you can combine to compose new functions. BiFunction<String, List<Article>, List<Article>> byAuthor = (name, articles) -> articles.stream() .filter(a -> a.getAuthor().equals(name)) .collect(Collectors.toList()); Function Composition
  • 24. BiFunction<String, List<Article>, List<Article>> byTag = (tag, articles) -> articles.stream() .filter(a -> a.getTags().contains(tag)) .collect(Collectors.toList()); Function<List<Article>, List<Article>> sortByDate = articles -> articles.stream() .sorted((x, y) -> y.published().compareTo(x.published())) .collect(Collectors.toList()); Function Composition
  • 25. Function<List<Article>, Optional<Article>> first = a -> a.stream().findFirst(); Function<List<Article>, Optional<Article>> newest = first.compose(sortByDate); BiFunction<String, List<Article>, List<Article>> byAuthorSorted = byAuthor.andThen(sortByDate); Function Composition
  • 26. The compose method uses a parameter named, before, and the andThen method uses a parameter named, after. These names indicate the order that the functions will be evaluated on. f(x) = (2+x)*3 g(x) = 2 +(x*3) Use compose and andThen to form f(x) and g(x). Function Composition
  • 27. Function<Integer, Integer> baseFunction = t -> t + 2; Function<Integer, Integer> afterFunction = baseFunction.andThen(t -> t * 3); System.out.println(afterFunction.apply(5)); Function<Integer, Integer> beforeFunction = baseFunction.compose(t -> t * 3); System.out.println(beforeFunction.apply(5)); when the apply method is executed, the corresponding lambda expression is executed Function Composition
  • 28. int hoursWorked[] = {8, 12, 8, 6, 6, 5, 6, 0}; int totalHoursWorked = Arrays.stream(hoursWorked) .filter(n -> n > 6) .sum(); LocalDateTime timeInstance = LocalDateTime.now() .plusDays(3) .minusHours(4) .plusWeeks(1) .plusYears(2); Fluent Interfaces
  • 29. Partial application is a way to turn a function that expects multiple parameters into one that will keep returning a new function until it receives all its arguments const f = (a,b,c) => a * b *c const g = partial(f,[2,3]) const h = g(4) Partial Application
  • 30. const applyTax = (amount,tax) => amount + (amount * tax) applyTax(0.08) => applyTaxOfEightPercent = partial(applyTax,[0.08]); applyTaxOfFivePercent = partial(applyTax,[0.05]); applyTaxofEightPercent(100); applyTaxofFivePercent(100); Exercise - Template design pattern. Try implementing it using partial application. Partial Application
  • 31. Currying is the process of taking a function that accepts N arguments and turning it into a chained series of N functions that each take one argument. The difference between partial application and currying is that with currying, you can never provide more than one argument — it has to be either one or zero. If a function takes 5 arguments, we can partially apply 3 of them. But with currying, we only pass one argument at a time. So if a function takes 5 arguments, we have to curry 5 times before we get the resulting value. Future and Promise are an application of currying. Currying