SlideShare a Scribd company logo
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)
Gentle Introduction to Functional Programming
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
Ad

More Related Content

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...
ssuserd6b1fd
 
Container adapters
Container adaptersContainer adapters
Container adapters
mohamed sikander
 
Excel function
Excel functionExcel function
Excel function
SirajRock
 
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
Alamgir Hossain
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Uma mohan
 
Intro to matlab
Intro to matlabIntro to matlab
Intro to matlab
Norhan Mohamed
 
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
Chris Eargle
 
Ss matlab solved
Ss matlab solvedSs matlab solved
Ss matlab solved
Vijendrasingh Rathor
 
Funções 4
Funções 4Funções 4
Funções 4
KalculosOnline
 
Class list data structure
Class list data structureClass list data structure
Class list data structure
Katang Isip
 
Unit 3
Unit 3 Unit 3
Unit 3
GOWSIKRAJAP
 
Lec9
Lec9Lec9
Lec9
Anjneya Varshney
 
c programming
c programmingc programming
c programming
Arun Umrao
 
Project2
Project2Project2
Project2
?? ?
 
Algorithm Assignment Help
Algorithm Assignment HelpAlgorithm Assignment Help
Algorithm Assignment Help
Programming Homework Help
 
Computer Programming- Lecture 7
Computer Programming- Lecture 7Computer Programming- Lecture 7
Computer Programming- Lecture 7
Dr. Md. Shohel Sayeed
 
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
 
Algorithms DM
Algorithms DMAlgorithms DM
Algorithms DM
Rokonuzzaman Rony
 
C sharp 8
C sharp 8C sharp 8
C sharp 8
Germán Küber
 
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 function
SirajRock
 
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
Alamgir Hossain
 
Computer graphics lab manual
Computer graphics lab manualComputer graphics lab manual
Computer graphics lab manual
Uma 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 Expressions
Chris Eargle
 
Class list data structure
Class list data structureClass list data structure
Class list data structure
Katang 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
 

Similar to Gentle Introduction to Functional Programming (20)

chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
chetanvchaudhari
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
SankarTerli
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet 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.ppt
SoumyaJ3
 
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
Yung-Yu Chen
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
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
Sunil 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.0
Sheik 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.ppt
AnishaJ7
 
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
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
Emertxe Information Technologies Pvt Ltd
 
Basic Python Programs, Python Fundamentals.pptx
Basic Python Programs, Python Fundamentals.pptxBasic Python Programs, Python Fundamentals.pptx
Basic Python Programs, Python Fundamentals.pptx
SrinivasGopalan2
 
Array
ArrayArray
Array
Malainine Zaid
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
C# introduzione per cibo e altri usi vati
C# introduzione per cibo e altri usi vatiC# introduzione per cibo e altri usi vati
C# introduzione per cibo e altri usi vati
AlessandroSiroCampi
 
Arrays
ArraysArrays
Arrays
poonamchopra7975
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
ebinazer1
 
Ch no 4 Python Functions,Modules & packages.pptx
Ch no 4 Python Functions,Modules & packages.pptxCh no 4 Python Functions,Modules & packages.pptx
Ch no 4 Python Functions,Modules & packages.pptx
gboy4529248
 
Introducción a Elixir
Introducción a ElixirIntroducción a Elixir
Introducción a Elixir
Svet 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.ppt
SoumyaJ3
 
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
Yung-Yu Chen
 
Monadologie
MonadologieMonadologie
Monadologie
league
 
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
Sunil 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.0
Sheik 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.ppt
AnishaJ7
 
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
 
Basic Python Programs, Python Fundamentals.pptx
Basic Python Programs, Python Fundamentals.pptxBasic Python Programs, Python Fundamentals.pptx
Basic Python Programs, Python Fundamentals.pptx
SrinivasGopalan2
 
Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語Haskellで学ぶ関数型言語
Haskellで学ぶ関数型言語
ikdysfm
 
C# introduzione per cibo e altri usi vati
C# introduzione per cibo e altri usi vatiC# introduzione per cibo e altri usi vati
C# introduzione per cibo e altri usi vati
AlessandroSiroCampi
 
chapter1.ppt
chapter1.pptchapter1.ppt
chapter1.ppt
ebinazer1
 
Ch no 4 Python Functions,Modules & packages.pptx
Ch no 4 Python Functions,Modules & packages.pptxCh no 4 Python Functions,Modules & packages.pptx
Ch no 4 Python Functions,Modules & packages.pptx
gboy4529248
 
Ad

Recently uploaded (20)

15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Metal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistryMetal alkyne complexes.pptx in chemistry
Metal alkyne complexes.pptx in chemistry
mee23nu
 
Data Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptxData Structures_Linear data structures Linked Lists.pptx
Data Structures_Linear data structures Linked Lists.pptx
RushaliDeshmukh2
 
LECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's usesLECTURE-16 EARTHEN DAM - II.pptx it's uses
LECTURE-16 EARTHEN DAM - II.pptx it's uses
CLokeshBehera123
 
theory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptxtheory-slides-for react for beginners.pptx
theory-slides-for react for beginners.pptx
sanchezvanessa7896
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
Data Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptxData Structures_Searching and Sorting.pptx
Data Structures_Searching and Sorting.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
How to use nRF24L01 module with Arduino
How to use nRF24L01 module with ArduinoHow to use nRF24L01 module with Arduino
How to use nRF24L01 module with Arduino
CircuitDigest
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
211421893-M-Tech-CIVIL-Structural-Engineering-pdf.pdf
inmishra17121973
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdffive-year-soluhhhhhhhhhhhhhhhhhtions.pdf
five-year-soluhhhhhhhhhhhhhhhhhtions.pdf
AdityaSharma944496
 
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptxLidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
Lidar for Autonomous Driving, LiDAR Mapping for Driverless Cars.pptx
RishavKumar530754
 
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITYADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ADVXAI IN MALWARE ANALYSIS FRAMEWORK: BALANCING EXPLAINABILITY WITH SECURITY
ijscai
 
Ad

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)
  • 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