SlideShare a Scribd company logo
1 of 18
Download to read offline
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

More Related Content

What's hot

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...ssuserd6b1fd
 
Excel function
Excel functionExcel function
Excel functionSirajRock
 
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 cppAlamgir Hossain
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manualUma mohan
 
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 ExpressionsChris Eargle
 
Class list data structure
Class list data structureClass list data structure
Class list data structureKatang Isip
 
Project2
Project2Project2
Project2?? ?
 
Finding root of equation (numarical method)
Finding root of equation (numarical method)Finding root of equation (numarical method)
Finding root of equation (numarical method)Rajan Thakkar
 

What's hot (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 to Gentle Introduction to Functional Programming

Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a ElixirSvet Ivantchev
 
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...Codemotion
 
Basic_analysis.ppt
Basic_analysis.pptBasic_analysis.ppt
Basic_analysis.pptSoumyaJ3
 
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 SpeedYung-Yu Chen
 
Monadologie
MonadologieMonadologie
Monadologieleague
 
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 ProblemsSunil Yadav
 
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.0Sheik Uduman Ali
 
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.pptAnishaJ7
 
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
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語ikdysfm
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.pptebinazer1
 
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 duoThe Software House
 
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.pptxssuser3cbb4c
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 

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

Recently uploaded

kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadhamedmustafa094
 
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 ptxJIT KUMAR GUPTA
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
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 PPTbhaskargani46
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersMairaAshraf6
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilVinayVitekari
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxchumtiyababu
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...drmkjayanthikannan
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
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 MunicipalityMorshed Ahmed Rahath
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdfKamal Acharya
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptNANDHAKUMARA10
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapRishantSharmaFr
 

Recently uploaded (20)

kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
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
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
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
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
Unit 4_Part 1 CSE2001 Exception Handling and Function Template and Class Temp...
 
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
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
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
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Block diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.pptBlock diagram reduction techniques in control systems.ppt
Block diagram reduction techniques in control systems.ppt
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 

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