SlideShare une entreprise Scribd logo
1  sur  18
Télécharger pour lire hors ligne
Functional Programming
(In an oops culture)
What is functional programming (FP)
 It is a programming paradigm and not a programming technique
 Broadly speaking it’s the philosophy of programming which dictates that the
building blocks of code should be “pure functions”
 The idea is to model computational problems in terms of mathematical
formulation.
 This usually means writing code with functions which excel at doing one thing
and doing it great.
 The data structures in functional programming are usually immutable
Pure functions
 T square(T x) { return x*x; }
 bool find(Container<T> items, T item) { for (auto x : items) if (x == item)
return true; return false; }
 void WillDoSomething(T *value) { *value = DidSomething(); }
 std::sort(T start, T end);
 T WillDoSomething() { return DidSomething(); }
 Data structures in FP based code are mostly immutable.
 Immutable data structures + pure functions = Highly parallelizable code
Making containers parallelizable?
Iterators
 Expose an iterator interface.
For eg all typical stl containers support iterator pattern.
bool Find(const Container<Type> &list, const Type &t) noexcept
{
for(const auto &x : list) { if (x==t) return true;}
return false;
}
Notice this find is actually a “pure” function.

Generators
 Generators are like iterators except that the items are generated on demand.
 (Python demo)
 A relatively good example in c++ of generators would be input iterators
while(cin >> value)
{
// Do something
}
Although this does explains what generators are supposed to do, it doesn’t do
justice to the power of generators.
The true power of generators
Problem : write a function that returns the sum of all primes <= N.
A trivial implementation would be:
int sumOfPrime(int N){
if ( N <= 1) return 0;
int sm = 2;
for (int i = 3;i <= N;i+=2) {
if (isPrime(i)){
sm += i;
}
}
return sm;
}
The Problem with this approach is that for each number i s.t. 0 <=i <= N one will necessarily have
to make sqrt(i) iterations taking the worst case to O(N*sqrt(N))
void primeSieve(int N, function doOnPrimes){
vector<bool> sieve(N + 1, 1);
sieve[2] = true;
doOnPrimes(2);
for (int i = 3; i <= N; i+=2){
if(sieve[i]){
doOnPrimes(i);
for(j=3*i; j <= N; j+=2*i) sieive[j] = false;
}
}
}
int sumOfPrimes(int N){
if (N <=1 ) return 1;
int sm = 0;
primeSieve(N, [&sm](int prime){ sm+= prime; });
return sm;
}
Using the sieve the asymptotic complexity remains the same but fewer iterations are made
But….
 Still not a good example of generator
 sumOfPrime needs to keep a state which sort of violates the principles of FP
 That is an important limitation for scalability
Yield keyword
generator<int> primeSieve(int N){
yield 2;
vector<bool> sieve(N + 1, 1);
for (int i = 3; i <= N; i+=2){
if(sieve[i]){
yield i;
for(j=3*i; j <= N; j+=2*i) sieve[j] = false;
}
}
yield break;
}
int sumOfPrimes(int N)
{
int sm = 0;
for (auto var : primeSieve(N)) sm += var;
return sm;
}
(Code shared here: https://github.com/bashrc-
real/Codearchive/tree/master/YeildTry)
Lambdas and closures
 Lambdas are anonymous functions
 Used for returning from higher order functions* or to be passed to higher
order functions
 Closures are lambdas with state
auto square = [](int x) { return x*x; } -> Lambda
auto squareAndSum = [value](int x) { return (x*x) + value; } -> Closure
MapReduce
 Map: Given a list map each value to another value. The mapping function must not
depend on the state of the list
 reduce : given a list transform the value to a single value
 For eg
Problem : Find the sum of all squares of [0,b]
List -> {0, 1, 2, 3…….b} [equivalent of vector<int> l(b); iota(l.begin(), l.end(), 0); }
Map-> [](int x) { return x*x; }
Reduce -> [](list values) { return accumulate(values.begin(), values.end(), 0); }
Combining the two:
transform(input.begin(), input.end(), output.begin(), [](int x) { return x*x; })
accumulate(output.begin(), output.end(), 0)
MapReduce(contd.)
 Notice that the steps of map reduce can be concatenated
Problem: Find whether a word exists among all words on the internet
Word: “Chewbacca”
MapReduce solution:
1. Define a map function such that [](string x) { int sm = 0; for(auto var:x)
sm+=var; return {x, sm%MOD;} }
2. After running the map on all strings the result will look something like
[DarthVader,7] [Yoda, 0] [Luke,5] [anakinSkyWalker,0]…..
Now we define a reduce function which returns a list of list of the form:
[0->{AnakinSkyWalker, Yoda}, 1->{HanSolo, …}, 2->{…},….]
3. We know the value of Chewbacca = 1 from the map function
4. We take the list with “key value” as 1
[0->{AnakinSkyWalker, Yoda}, 1->{HanSolo, …}, 2->{…},….]
5. We can now apply steps 1-4 each time with probably a new hash function and
at each step after reduce the size of the list will keep getting smaller
6. Eventually the list will be so small that we can iterate through the list and
match the strings character by character to our search string
7. Chewbacca does exist in star wars universe 
Conclusion
 Small stateless functions = testability, easier debugging, less bugs, such
amaze much wow.
 Easy to scale and expand the program to take advantage of multi-cores
without changing the logic
 More power to the compiler
References
 https://wiki.haskell.org/Functional_programming
 http://stackoverflow.com/questions/715758/coroutine-vs-continuation-vs-
generator
 https://en.wikipedia.org/wiki/Higher-order_function

Contenu connexe

Tendances

11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng
웅식 전
 
Project2
Project2Project2
Project2
?? ?
 

Tendances (20)

Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
Notes for C Programming for MCA, BCA, B. Tech CSE, ECE and MSC (CS) 4 of 5 by...
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
Excel function
Excel functionExcel function
Excel function
 
Computer graphics lab report with code in cpp
Computer graphics lab report with code in cppComputer graphics lab report with code in cpp
Computer graphics lab report with code in cpp
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
 
Intro to matlab
Intro to matlabIntro to matlab
Intro to matlab
 
11 1. multi-dimensional array eng
11 1. multi-dimensional array eng11 1. multi-dimensional array eng
11 1. multi-dimensional array eng
 
Monadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query ExpressionsMonadic Comprehensions and Functional Composition with Query Expressions
Monadic Comprehensions and Functional Composition with Query Expressions
 
Ss matlab solved
Ss matlab solvedSs matlab solved
Ss matlab solved
 
Funções 4
Funções 4Funções 4
Funções 4
 
Class list data structure
Class list data structureClass list data structure
Class list data structure
 
Unit 3
Unit 3 Unit 3
Unit 3
 
Lec9
Lec9Lec9
Lec9
 
c programming
c programmingc programming
c programming
 
Project2
Project2Project2
Project2
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
 
Finding root of equation (numarical method)
Finding root of equation (numarical method)Finding root of equation (numarical method)
Finding root of equation (numarical method)
 
Algorithms DM
Algorithms DMAlgorithms DM
Algorithms DM
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
 

Similaire à Gentle Introduction to Functional Programming

Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Mario Fusco
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 

Similaire à Gentle Introduction to Functional Programming (20)

chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Basic_analysis.ppt
Basic_analysis.pptBasic_analysis.ppt
Basic_analysis.ppt
 
An Introduction to Part of C++ STL
An Introduction to Part of C++ STLAn Introduction to Part of C++ STL
An Introduction to Part of C++ STL
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
Monadologie
MonadologieMonadologie
Monadologie
 
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm ProblemsLeet Code May Coding Challenge - DataStructure and Algorithm Problems
Leet Code May Coding Challenge - DataStructure and Algorithm Problems
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
Array
ArrayArray
Array
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
 
Arrays
ArraysArrays
Arrays
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 

Dernier

Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 

Gentle Introduction to Functional Programming

  • 2. What is functional programming (FP)  It is a programming paradigm and not a programming technique  Broadly speaking it’s the philosophy of programming which dictates that the building blocks of code should be “pure functions”  The idea is to model computational problems in terms of mathematical formulation.  This usually means writing code with functions which excel at doing one thing and doing it great.  The data structures in functional programming are usually immutable
  • 3. Pure functions  T square(T x) { return x*x; }  bool find(Container<T> items, T item) { for (auto x : items) if (x == item) return true; return false; }  void WillDoSomething(T *value) { *value = DidSomething(); }  std::sort(T start, T end);  T WillDoSomething() { return DidSomething(); }  Data structures in FP based code are mostly immutable.  Immutable data structures + pure functions = Highly parallelizable code
  • 4. Making containers parallelizable? Iterators  Expose an iterator interface. For eg all typical stl containers support iterator pattern. bool Find(const Container<Type> &list, const Type &t) noexcept { for(const auto &x : list) { if (x==t) return true;} return false; } Notice this find is actually a “pure” function.
  • 5.
  • 6. Generators  Generators are like iterators except that the items are generated on demand.  (Python demo)  A relatively good example in c++ of generators would be input iterators while(cin >> value) { // Do something } Although this does explains what generators are supposed to do, it doesn’t do justice to the power of generators.
  • 7. The true power of generators Problem : write a function that returns the sum of all primes <= N. A trivial implementation would be: int sumOfPrime(int N){ if ( N <= 1) return 0; int sm = 2; for (int i = 3;i <= N;i+=2) { if (isPrime(i)){ sm += i; } } return sm; } The Problem with this approach is that for each number i s.t. 0 <=i <= N one will necessarily have to make sqrt(i) iterations taking the worst case to O(N*sqrt(N))
  • 8. void primeSieve(int N, function doOnPrimes){ vector<bool> sieve(N + 1, 1); sieve[2] = true; doOnPrimes(2); for (int i = 3; i <= N; i+=2){ if(sieve[i]){ doOnPrimes(i); for(j=3*i; j <= N; j+=2*i) sieive[j] = false; } } } int sumOfPrimes(int N){ if (N <=1 ) return 1; int sm = 0; primeSieve(N, [&sm](int prime){ sm+= prime; }); return sm; } Using the sieve the asymptotic complexity remains the same but fewer iterations are made
  • 9. But….  Still not a good example of generator  sumOfPrime needs to keep a state which sort of violates the principles of FP  That is an important limitation for scalability
  • 10. Yield keyword generator<int> primeSieve(int N){ yield 2; vector<bool> sieve(N + 1, 1); for (int i = 3; i <= N; i+=2){ if(sieve[i]){ yield i; for(j=3*i; j <= N; j+=2*i) sieve[j] = false; } } yield break; }
  • 11. int sumOfPrimes(int N) { int sm = 0; for (auto var : primeSieve(N)) sm += var; return sm; } (Code shared here: https://github.com/bashrc- real/Codearchive/tree/master/YeildTry)
  • 12.
  • 13. Lambdas and closures  Lambdas are anonymous functions  Used for returning from higher order functions* or to be passed to higher order functions  Closures are lambdas with state auto square = [](int x) { return x*x; } -> Lambda auto squareAndSum = [value](int x) { return (x*x) + value; } -> Closure
  • 14. MapReduce  Map: Given a list map each value to another value. The mapping function must not depend on the state of the list  reduce : given a list transform the value to a single value  For eg Problem : Find the sum of all squares of [0,b] List -> {0, 1, 2, 3…….b} [equivalent of vector<int> l(b); iota(l.begin(), l.end(), 0); } Map-> [](int x) { return x*x; } Reduce -> [](list values) { return accumulate(values.begin(), values.end(), 0); } Combining the two: transform(input.begin(), input.end(), output.begin(), [](int x) { return x*x; }) accumulate(output.begin(), output.end(), 0)
  • 15. MapReduce(contd.)  Notice that the steps of map reduce can be concatenated Problem: Find whether a word exists among all words on the internet Word: “Chewbacca” MapReduce solution: 1. Define a map function such that [](string x) { int sm = 0; for(auto var:x) sm+=var; return {x, sm%MOD;} } 2. After running the map on all strings the result will look something like [DarthVader,7] [Yoda, 0] [Luke,5] [anakinSkyWalker,0]….. Now we define a reduce function which returns a list of list of the form: [0->{AnakinSkyWalker, Yoda}, 1->{HanSolo, …}, 2->{…},….] 3. We know the value of Chewbacca = 1 from the map function
  • 16. 4. We take the list with “key value” as 1 [0->{AnakinSkyWalker, Yoda}, 1->{HanSolo, …}, 2->{…},….] 5. We can now apply steps 1-4 each time with probably a new hash function and at each step after reduce the size of the list will keep getting smaller 6. Eventually the list will be so small that we can iterate through the list and match the strings character by character to our search string 7. Chewbacca does exist in star wars universe 
  • 17. Conclusion  Small stateless functions = testability, easier debugging, less bugs, such amaze much wow.  Easy to scale and expand the program to take advantage of multi-cores without changing the logic  More power to the compiler