SlideShare una empresa de Scribd logo
1 de 18
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
?? ?
 

La actualidad más candente (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
 

Similar a 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
 

Similar a 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
 

Último

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Dr.Costas Sachpazis
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
rknatarajan
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Último (20)

Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
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
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and workingUNIT-V FMM.HYDRAULIC TURBINE - Construction and working
UNIT-V FMM.HYDRAULIC TURBINE - Construction and working
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 

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