SlideShare a Scribd company logo
1 of 30
Download to read offline
Functional Programming in
C++
An Overview
▪ Programming in a
functional style
▪ Why functional
programming?
▪ What is functional
programming?
▪ Characteristics of
functional programming
▪ What's missing?
Functional in C++
▪ Automatic type deduction
for ( auto v: myVec ) std::cout << v << " ";
▪ Lambda-functions
int a= 2000, b= 11;
auto sum= std::async( [=]{return a+b;});
▪ Partial function application
std::function and std::bind
lambda-functions and auto
Haskell Curry Moses Schönfinkel
Functional in C++
▪ Higher-order functions
std::vec<int> vec{1,2,3,4,5,6,7,8,9};
std::for_each(vec.begin(),vec.end(), [ ] (int& v) { v+= 10 });
std::for_each( vec.begin(),vec.end(),
[ ] (int v){ cout << " " << v } );
11 12 13 14 15 16 17 18 19
▪ Generic Programming (Templates)
▪ Standard Template Library
▪ Template Metaprogramming
Alexander Stepanov
Why functional?
▪ More effective use of the Standard Template Library
std::accumulate(vec.begin(),vec.end(),
" "[](int a, int b){return a+b;});
▪ Recognizing functional patterns
template <int N>
struct Fac{ static int const val= N * Fac<N-1>::val; };
template <>
struct Fac<0>{ static int const val= 1; };
▪ Better programming style
▪ reasoning about side effects
▪ more concise
Functional programming?
▪ Functional programming is programming with mathematical
functions.
▪ Mathematical functions are functions that each time return the
same value when given the same arguments (referential
transparency).
▪ Consequences:
▪ Functions are not allowed to have side effects.
▪ The function invocation can be replaced by the result,
rearranged or given to an other thread.
▪ The program flow will be driven by the data dependencies.
Characteristics
Characteristics of
functional
programing
First-class
functions
Higher-order
functions
Immutable data
Pure functionsRecursion
Manipulation
of lists
Lazy evaluation
First-class functions
▪ First-class functions are first-class
citizens.
Functions are like data.
▪ Functions
▪ can be passed as arguments to
other functions.
▪ can be returned from other
functions.
▪ can be assigned to variables or
stored in a data structure.
First-class functions
std::map<const char,function< double(double,double)> > tab;
tab.insert(std::make_pair('+',[](double a,double b){return a + b;}));
tab.insert(std::make_pair('-',[](double a,double b){return a - b;}));
tab.insert(std::make_pair('*',[](double a,double b){return a * b;}));
tab.insert(std::make_pair('/',[](double a,double b){return a / b;}));
cout << "3.5+4.5= " << tab['+'](3.5,4.5) << endl; 8
cout << "3.5*4.5= " << tab['*'](3.5,4.5) << endl; 15.75
tab.insert(std::make_pair('^',
[](double a,double b){return std::pow(a,b);}));
cout << "3.5^4.5= " << tab['^'](3.5,4.5) << endl; 280.741
Higher-order functions
Higher-order functions are functions that accept other functions
as argument or return them as result.
▪ The three classics:
▪ map:
Apply a function to each element of
a list.
▪ filter:
Remove elements from a list.
▪ fold:
Reduce a list to a single value by successively applying a
binary operation.
(source: http://musicantic.blogspot.de, 2012-10-16)
Higher-order functions
▪ Each programming language supporting programming in a
functional style offers map, filter and fold.
▪ map, filter and fold are 3 powerful functions which are applicable in
many cases.
map + reduce= MapReduce
Haskell Python C++
map map std::transform
filter filter std::remove_if
fold* reduce std::accumulate
Higher-order functions
▪ Lists and vectors:
▪ Haskell
vec= [1 . . 9]
str= ["Programming","in","a","functional","style."]
▪ Python
vec=range(1,10)
str=["Programming","in","a","functional","style."]
▪ C++
std::vector<int> vec{1,2,3,4,5,6,7,8,9}
std::vector<string>str{"Programming","in","a","functional",
"style."}
The results will be displayed in Haskell or Python notation.
Higher-order functions: map
▪ Haskell
map(a → a^2) vec
map(a -> length a) str
▪ Python
map(lambda x : x*x , vec)
map(lambda x : len(x),str)
▪ C++
std::transform(vec.begin(),vec.end(),vec.begin(),
" "[](int i){ return i*i; });
std::transform(str.begin(),str.end(),back_inserter(vec2),
" "[](std::string s){ return s.length(); });
[1,4,9,16,25,36,49,64,81]
[11,2,1,10,6]
Higher-order functions: filter
▪ Haskell
filter(x-> x<3 || x>8) vec
filter(x → isUpper(head x)) str
▪ Python
filter(lambda x: x<3 or x>8 , vec)
filter(lambda x: x[0].isupper(),str)
▪ C++
auto it= std::remove_if(vec.begin(),vec.end(),
[](int i){ return !((i < 3) or (i > 8)) });
auto it2= std::remove_if(str.begin(),str.end(),
" "[](string s){ return !(isupper(s[0])); });
[1,2,9]
[“Programming”]
Higher-order functions: fold
▪ Haskell:
foldl (a b → a * b) 1 vec
foldl (a b → a ++ ":" ++ b ) "" str
▪ Python:
reduce(lambda a , b: a * b, vec, 1)
reduce(lambda a, b: a + b, str,"")
▪ C++:
std::accumulate(vec.begin(),vec.end(),1,
" " [](int a, int b){ return a*b; });
std::accumulate(str.begin(),str.end(),string(""),
" "[](string a,string b){ return a+":"+b; });
362800
“:Programming:in:a:functional:style.”
Higher-order functions: fold
std::vector<int> v{1,2,3,4};
std::accumulate(v.begin(),v.end(),1,[](int a, int b){return a*b;});
1 * { 1 , 2 , 3 , 4 }
1 * 1
=
1 * 2
=
2 * 3
=
6 * 4 = 24
Immutable data
Data are immutable in pure functional languages.
Distinction between variables and values
▪ Consequences
▪ There is no
▪ Assignment: x= x + 1, ++x
▪ Loops: for, while , until
▪ In case of data modification
▪ changed copies of the data will be generated.
▪ the original data will be shared.
Immutable data are thread safe.
Immutable data
• Haskell
qsort [] = []
qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x]
• C++
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int tmp;
int pivot = arr[abs((left + right) / 2)];
while (i <= j) {
while (arr[i] < pivot) i++;
while (arr[j] > pivot) j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++; j--;
}
}
if (left < j) quickSort(arr,left,j);
if (i < right) quickSort(arr,i,right);
}
Pure functions
▪ Advantages
▪ Correctness of the code is easier to verify.
▪ Refactor and test is possible
▪ Saving results of pure function invocations.
▪ Reordering pure function invocations or performing them on other
threads.
Pure functions Impure functions
Always produce the same result
when given the same parameters.
May produce different results for the
same parameters.
Never have side effects. May have side effects.
Never alter state. May alter the global state of the
program, system, or world.
Pure functions
▪ Monads are the Haskell solution to deal with the impure world.
▪ A Monad
▪ encapsulates the impure world.
▪ is a imperative subsystem in.
▪ represents a computation structure.
▪ define the composition of computations.
▪ Examples:
▪ I/O monad for input and output
▪ Maybe monad for computations that can fail
▪ List monad for computations with zero or more valid answers
▪ State monad for stateful computation
▪ STM monad for software transactional memory
Recursion
▪ Recursion is the control structure in functional programming.
▪ A loop (for int i=0; i <= 0; ++i) needs a variable i.
Recursion combined with list processing is a powerful pattern in
functional languages.
Recursion
▪ Haskell:
fac 0= 1
fac n= n * fac (n-1)
▪ C++:
template<int N>
struct Fac{
static int const value= N * Fac<N-1>::value;
};
template <>
struct Fac<0>{
static int const value = 1;
};
fac(5) == Fac<5>::value == 120
List processing
▪ LISt Processing is the characteristic for functional programming:
▪ transforming a list into another list
▪ reducing a list to a value
▪ The functional pattern for list processing:
1. Processing the head (x) of the list
2. Recursively processing the tail (xs) of the list => Go to step 1).
mySum [] = 0
mySum (x:xs) = x + mySum xs
mySum [1,2,3,4,5] 15
myMap f [] = []
myMap f (x:xs)= f x: myMap f xs
myMap (x → x*x)[1,2,3] [1,4,9]
List processing
template<int ...> struct mySum;
template<>struct
mySum<>{
static const int value= 0;
};
template<int i, int ... tail> struct
mySum<i,tail...>{
static const int value= i + mySum<tail...>::value;
};
int sum= mySum<1,2,3,4,5>::value; sum == 15
List processing
▪ The key idea behind list processing is pattern matching.
▪ First match in Haskell
mult n 0 = 0
mult n 1 = n
mult n m = (mult n (m – 1)) + n
mult 3 2 = (mult 3 (2 – 1)) + 3
= (mult 3 1 ) + 3
= 3 + 3
= 6
▪ Best match in C++11
template < int N1, int N2 > class Mult { … };
template < int N1 > class Mult <N1,1> { … };
template < int N1 > class Mult <N1,0> { … };
Lazy Evaluation
▪ Evaluate only, if necessary.
▪ Haskell is lazy
length [2+1, 3*2, 1/0, 5-4]
▪ C++ is eager
int onlyFirst(int a, int){ return a; }
onlyFirst(1,1/0);
▪ Advantages:
▪ Saving time and memory usage
▪ Working with infinite data structures
Lazy Evaluation
▪ Haskell
successor i= i: (successor (i+1))
take 5 ( successor 10 ) [10,11,12,13,14]
odds= takeWhile (< 1000) . filter odd . map (^2)
[1..]= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ... Control-C
odds [1..] [1,9,25, … , 841,961]
▪ Special case in C++: short circuit evaluation
if ( true or (1/0) ) std::cout << "short circuit evaluation in C++n";
What's missing?
▪ List comprehension: Syntactic sugar for map and filter
▪ Like mathematic
{ n*n | n e N , n mod 2 = 0 } : Mathematik
[n*n | n <- [1..], n `mod` 2 == 0 ] : Haskell
▪ Python
[n for n in range(8)] [0,1,2,3,4,5,6,7]
[n*n for n in range(8)] [0,1,4,9,16,25,36,49]
[n*n for n in range(8) if n%2 == 0] [0,4,16,36]
What's missing?
Function composition: fluent interface
▪ Haskell
(reverse . sort)[10,2,8,1,9,5,3,6,4,7]
[10,9,8,7,6,5,4,3,2,1]
isTit (x:xs)= isUpper x && all isLower xs
sorTitLen= sortBy(comparing length).filter isTit . words
sorTitLen “A Sentence full of Titles .“
[“A“,“Titles“,“Sentence“]
25.10.2014 | Metrax GmbH | Seite 30
Rainer Grimm
www.primedic.com
phone +49 (0)741 257-245
rainer.grimm@primedic.com

More Related Content

What's hot

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsAlexander Granin
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88Mahmoud Samir Fayed
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"OdessaJS Conf
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...GeeksLab Odessa
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»SpbDotNet Community
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!mickey24
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)hhliu
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++vidyamittal
 
C++totural file
C++totural fileC++totural file
C++totural filehalaisumit
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project FileDeyvessh kumar
 

What's hot (20)

DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonads
 
The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88The Ring programming language version 1.3 book - Part 84 of 88
The Ring programming language version 1.3 book - Part 84 of 88
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»Дмитрий Верескун «Синтаксический сахар C#»
Дмитрий Верескун «Синтаксический сахар C#»
 
Bind me if you can
Bind me if you canBind me if you can
Bind me if you can
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
 
Container adapters
Container adaptersContainer adapters
Container adapters
 
C programs
C programsC programs
C programs
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
C program
C programC program
C program
 
Advance features of C++
Advance features of C++Advance features of C++
Advance features of C++
 
C++totural file
C++totural fileC++totural file
C++totural file
 
Data Structure Project File
Data Structure Project FileData Structure Project File
Data Structure Project File
 

Viewers also liked

Coding Dojo: Fun with Tic-Tac-Toe (2014)
Coding Dojo: Fun with Tic-Tac-Toe (2014)Coding Dojo: Fun with Tic-Tac-Toe (2014)
Coding Dojo: Fun with Tic-Tac-Toe (2014)Peter Kofler
 
Serial Killers Psychology Presentation
Serial Killers Psychology PresentationSerial Killers Psychology Presentation
Serial Killers Psychology PresentationPietro Solda
 
Network Security and Cryptography
Network Security and CryptographyNetwork Security and Cryptography
Network Security and CryptographyAdam Reagan
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
15 10-22 altoros-fact_sheet_st_v4
15 10-22 altoros-fact_sheet_st_v415 10-22 altoros-fact_sheet_st_v4
15 10-22 altoros-fact_sheet_st_v4Olga Lavrentieva
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with pythonMarcelo Cure
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionagedgnadt
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5zukun
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANSheikh Hasnain
 

Viewers also liked (20)

Coding Dojo: Fun with Tic-Tac-Toe (2014)
Coding Dojo: Fun with Tic-Tac-Toe (2014)Coding Dojo: Fun with Tic-Tac-Toe (2014)
Coding Dojo: Fun with Tic-Tac-Toe (2014)
 
Serial Killers Psychology Presentation
Serial Killers Psychology PresentationSerial Killers Psychology Presentation
Serial Killers Psychology Presentation
 
Android Basic Components
Android Basic ComponentsAndroid Basic Components
Android Basic Components
 
Network Security and Cryptography
Network Security and CryptographyNetwork Security and Cryptography
Network Security and Cryptography
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
15 10-22 altoros-fact_sheet_st_v4
15 10-22 altoros-fact_sheet_st_v415 10-22 altoros-fact_sheet_st_v4
15 10-22 altoros-fact_sheet_st_v4
 
SAN Review
SAN ReviewSAN Review
SAN Review
 
SAN
SANSAN
SAN
 
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012
 
Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
 
Securing Windows web servers
Securing Windows web serversSecuring Windows web servers
Securing Windows web servers
 
Noah Z - Spies
Noah Z - SpiesNoah Z - Spies
Noah Z - Spies
 
Trends in spies
Trends in spiesTrends in spies
Trends in spies
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
 
Lec 03 set
Lec 03   setLec 03   set
Lec 03 set
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
 
Functional style programming
Functional style programmingFunctional style programming
Functional style programming
 
Android UI
Android UIAndroid UI
Android UI
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHAN
 

Similar to Rainer Grimm, “Functional Programming in C++11”

Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovGeorgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScriptInnovecs
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in rubyKoen Handekyn
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen TatarynovFwdays
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinDmitry Pranchuk
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonAlex Payne
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programmingLukasz Dynowski
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskellujihisa
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35Bilal Ahmed
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
C++ process new
C++ process newC++ process new
C++ process new敬倫 林
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 

Similar to Rainer Grimm, “Functional Programming in C++11” (20)

Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
FunctionalJS - George Shevtsov
FunctionalJS - George ShevtsovFunctionalJS - George Shevtsov
FunctionalJS - George Shevtsov
 
1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript1. George Shevtsov - Functional JavaScript
1. George Shevtsov - Functional JavaScript
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Functional programming in ruby
Functional programming in rubyFunctional programming in ruby
Functional programming in ruby
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov"Optimization of a .NET application- is it simple ! / ?",  Yevhen Tatarynov
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Compact and safely: static DSL on Kotlin
Compact and safely: static DSL on KotlinCompact and safely: static DSL on Kotlin
Compact and safely: static DSL on Kotlin
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
Matlab1
Matlab1Matlab1
Matlab1
 
Python 101 language features and functional programming
Python 101 language features and functional programmingPython 101 language features and functional programming
Python 101 language features and functional programming
 
From Javascript To Haskell
From Javascript To HaskellFrom Javascript To Haskell
From Javascript To Haskell
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Mbd2
Mbd2Mbd2
Mbd2
 
CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35CS101- Introduction to Computing- Lecture 35
CS101- Introduction to Computing- Lecture 35
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
C++ process new
C++ process newC++ process new
C++ process new
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 

More from Platonov Sergey

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияPlatonov Sergey
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3Platonov Sergey
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Platonov Sergey
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеТененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеPlatonov Sergey
 
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxПавел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxPlatonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIPlatonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IPlatonov Sergey
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практикеPlatonov Sergey
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутовPlatonov Sergey
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Platonov Sergey
 
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Platonov Sergey
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийPlatonov Sergey
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Platonov Sergey
 
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Platonov Sergey
 
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияДракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияPlatonov Sergey
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьPlatonov Sergey
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыPlatonov Sergey
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузераPlatonov Sergey
 

More from Platonov Sergey (20)

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализация
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеТененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
 
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxПавел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практике
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутов
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++
 
C++ exceptions
C++ exceptionsC++ exceptions
C++ exceptions
 
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычислений
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08
 
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...
 
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияДракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим жить
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансы
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузера
 

Recently uploaded

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 

Recently uploaded (20)

SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 

Rainer Grimm, “Functional Programming in C++11”

  • 2. An Overview ▪ Programming in a functional style ▪ Why functional programming? ▪ What is functional programming? ▪ Characteristics of functional programming ▪ What's missing?
  • 3. Functional in C++ ▪ Automatic type deduction for ( auto v: myVec ) std::cout << v << " "; ▪ Lambda-functions int a= 2000, b= 11; auto sum= std::async( [=]{return a+b;}); ▪ Partial function application std::function and std::bind lambda-functions and auto Haskell Curry Moses Schönfinkel
  • 4. Functional in C++ ▪ Higher-order functions std::vec<int> vec{1,2,3,4,5,6,7,8,9}; std::for_each(vec.begin(),vec.end(), [ ] (int& v) { v+= 10 }); std::for_each( vec.begin(),vec.end(), [ ] (int v){ cout << " " << v } ); 11 12 13 14 15 16 17 18 19 ▪ Generic Programming (Templates) ▪ Standard Template Library ▪ Template Metaprogramming Alexander Stepanov
  • 5. Why functional? ▪ More effective use of the Standard Template Library std::accumulate(vec.begin(),vec.end(), " "[](int a, int b){return a+b;}); ▪ Recognizing functional patterns template <int N> struct Fac{ static int const val= N * Fac<N-1>::val; }; template <> struct Fac<0>{ static int const val= 1; }; ▪ Better programming style ▪ reasoning about side effects ▪ more concise
  • 6. Functional programming? ▪ Functional programming is programming with mathematical functions. ▪ Mathematical functions are functions that each time return the same value when given the same arguments (referential transparency). ▪ Consequences: ▪ Functions are not allowed to have side effects. ▪ The function invocation can be replaced by the result, rearranged or given to an other thread. ▪ The program flow will be driven by the data dependencies.
  • 8. First-class functions ▪ First-class functions are first-class citizens. Functions are like data. ▪ Functions ▪ can be passed as arguments to other functions. ▪ can be returned from other functions. ▪ can be assigned to variables or stored in a data structure.
  • 9. First-class functions std::map<const char,function< double(double,double)> > tab; tab.insert(std::make_pair('+',[](double a,double b){return a + b;})); tab.insert(std::make_pair('-',[](double a,double b){return a - b;})); tab.insert(std::make_pair('*',[](double a,double b){return a * b;})); tab.insert(std::make_pair('/',[](double a,double b){return a / b;})); cout << "3.5+4.5= " << tab['+'](3.5,4.5) << endl; 8 cout << "3.5*4.5= " << tab['*'](3.5,4.5) << endl; 15.75 tab.insert(std::make_pair('^', [](double a,double b){return std::pow(a,b);})); cout << "3.5^4.5= " << tab['^'](3.5,4.5) << endl; 280.741
  • 10. Higher-order functions Higher-order functions are functions that accept other functions as argument or return them as result. ▪ The three classics: ▪ map: Apply a function to each element of a list. ▪ filter: Remove elements from a list. ▪ fold: Reduce a list to a single value by successively applying a binary operation. (source: http://musicantic.blogspot.de, 2012-10-16)
  • 11. Higher-order functions ▪ Each programming language supporting programming in a functional style offers map, filter and fold. ▪ map, filter and fold are 3 powerful functions which are applicable in many cases. map + reduce= MapReduce Haskell Python C++ map map std::transform filter filter std::remove_if fold* reduce std::accumulate
  • 12. Higher-order functions ▪ Lists and vectors: ▪ Haskell vec= [1 . . 9] str= ["Programming","in","a","functional","style."] ▪ Python vec=range(1,10) str=["Programming","in","a","functional","style."] ▪ C++ std::vector<int> vec{1,2,3,4,5,6,7,8,9} std::vector<string>str{"Programming","in","a","functional", "style."} The results will be displayed in Haskell or Python notation.
  • 13. Higher-order functions: map ▪ Haskell map(a → a^2) vec map(a -> length a) str ▪ Python map(lambda x : x*x , vec) map(lambda x : len(x),str) ▪ C++ std::transform(vec.begin(),vec.end(),vec.begin(), " "[](int i){ return i*i; }); std::transform(str.begin(),str.end(),back_inserter(vec2), " "[](std::string s){ return s.length(); }); [1,4,9,16,25,36,49,64,81] [11,2,1,10,6]
  • 14. Higher-order functions: filter ▪ Haskell filter(x-> x<3 || x>8) vec filter(x → isUpper(head x)) str ▪ Python filter(lambda x: x<3 or x>8 , vec) filter(lambda x: x[0].isupper(),str) ▪ C++ auto it= std::remove_if(vec.begin(),vec.end(), [](int i){ return !((i < 3) or (i > 8)) }); auto it2= std::remove_if(str.begin(),str.end(), " "[](string s){ return !(isupper(s[0])); }); [1,2,9] [“Programming”]
  • 15. Higher-order functions: fold ▪ Haskell: foldl (a b → a * b) 1 vec foldl (a b → a ++ ":" ++ b ) "" str ▪ Python: reduce(lambda a , b: a * b, vec, 1) reduce(lambda a, b: a + b, str,"") ▪ C++: std::accumulate(vec.begin(),vec.end(),1, " " [](int a, int b){ return a*b; }); std::accumulate(str.begin(),str.end(),string(""), " "[](string a,string b){ return a+":"+b; }); 362800 “:Programming:in:a:functional:style.”
  • 16. Higher-order functions: fold std::vector<int> v{1,2,3,4}; std::accumulate(v.begin(),v.end(),1,[](int a, int b){return a*b;}); 1 * { 1 , 2 , 3 , 4 } 1 * 1 = 1 * 2 = 2 * 3 = 6 * 4 = 24
  • 17. Immutable data Data are immutable in pure functional languages. Distinction between variables and values ▪ Consequences ▪ There is no ▪ Assignment: x= x + 1, ++x ▪ Loops: for, while , until ▪ In case of data modification ▪ changed copies of the data will be generated. ▪ the original data will be shared. Immutable data are thread safe.
  • 18. Immutable data • Haskell qsort [] = [] qsort (x:xs) = qsort [y | y <- xs, y < x] ++ [x] ++ qsort [y | y <- xs, y >= x] • C++ void quickSort(int arr[], int left, int right) { int i = left, j = right; int tmp; int pivot = arr[abs((left + right) / 2)]; while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } if (left < j) quickSort(arr,left,j); if (i < right) quickSort(arr,i,right); }
  • 19. Pure functions ▪ Advantages ▪ Correctness of the code is easier to verify. ▪ Refactor and test is possible ▪ Saving results of pure function invocations. ▪ Reordering pure function invocations or performing them on other threads. Pure functions Impure functions Always produce the same result when given the same parameters. May produce different results for the same parameters. Never have side effects. May have side effects. Never alter state. May alter the global state of the program, system, or world.
  • 20. Pure functions ▪ Monads are the Haskell solution to deal with the impure world. ▪ A Monad ▪ encapsulates the impure world. ▪ is a imperative subsystem in. ▪ represents a computation structure. ▪ define the composition of computations. ▪ Examples: ▪ I/O monad for input and output ▪ Maybe monad for computations that can fail ▪ List monad for computations with zero or more valid answers ▪ State monad for stateful computation ▪ STM monad for software transactional memory
  • 21. Recursion ▪ Recursion is the control structure in functional programming. ▪ A loop (for int i=0; i <= 0; ++i) needs a variable i. Recursion combined with list processing is a powerful pattern in functional languages.
  • 22. Recursion ▪ Haskell: fac 0= 1 fac n= n * fac (n-1) ▪ C++: template<int N> struct Fac{ static int const value= N * Fac<N-1>::value; }; template <> struct Fac<0>{ static int const value = 1; }; fac(5) == Fac<5>::value == 120
  • 23. List processing ▪ LISt Processing is the characteristic for functional programming: ▪ transforming a list into another list ▪ reducing a list to a value ▪ The functional pattern for list processing: 1. Processing the head (x) of the list 2. Recursively processing the tail (xs) of the list => Go to step 1). mySum [] = 0 mySum (x:xs) = x + mySum xs mySum [1,2,3,4,5] 15 myMap f [] = [] myMap f (x:xs)= f x: myMap f xs myMap (x → x*x)[1,2,3] [1,4,9]
  • 24. List processing template<int ...> struct mySum; template<>struct mySum<>{ static const int value= 0; }; template<int i, int ... tail> struct mySum<i,tail...>{ static const int value= i + mySum<tail...>::value; }; int sum= mySum<1,2,3,4,5>::value; sum == 15
  • 25. List processing ▪ The key idea behind list processing is pattern matching. ▪ First match in Haskell mult n 0 = 0 mult n 1 = n mult n m = (mult n (m – 1)) + n mult 3 2 = (mult 3 (2 – 1)) + 3 = (mult 3 1 ) + 3 = 3 + 3 = 6 ▪ Best match in C++11 template < int N1, int N2 > class Mult { … }; template < int N1 > class Mult <N1,1> { … }; template < int N1 > class Mult <N1,0> { … };
  • 26. Lazy Evaluation ▪ Evaluate only, if necessary. ▪ Haskell is lazy length [2+1, 3*2, 1/0, 5-4] ▪ C++ is eager int onlyFirst(int a, int){ return a; } onlyFirst(1,1/0); ▪ Advantages: ▪ Saving time and memory usage ▪ Working with infinite data structures
  • 27. Lazy Evaluation ▪ Haskell successor i= i: (successor (i+1)) take 5 ( successor 10 ) [10,11,12,13,14] odds= takeWhile (< 1000) . filter odd . map (^2) [1..]= [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 ... Control-C odds [1..] [1,9,25, … , 841,961] ▪ Special case in C++: short circuit evaluation if ( true or (1/0) ) std::cout << "short circuit evaluation in C++n";
  • 28. What's missing? ▪ List comprehension: Syntactic sugar for map and filter ▪ Like mathematic { n*n | n e N , n mod 2 = 0 } : Mathematik [n*n | n <- [1..], n `mod` 2 == 0 ] : Haskell ▪ Python [n for n in range(8)] [0,1,2,3,4,5,6,7] [n*n for n in range(8)] [0,1,4,9,16,25,36,49] [n*n for n in range(8) if n%2 == 0] [0,4,16,36]
  • 29. What's missing? Function composition: fluent interface ▪ Haskell (reverse . sort)[10,2,8,1,9,5,3,6,4,7] [10,9,8,7,6,5,4,3,2,1] isTit (x:xs)= isUpper x && all isLower xs sorTitLen= sortBy(comparing length).filter isTit . words sorTitLen “A Sentence full of Titles .“ [“A“,“Titles“,“Sentence“]
  • 30. 25.10.2014 | Metrax GmbH | Seite 30 Rainer Grimm www.primedic.com phone +49 (0)741 257-245 rainer.grimm@primedic.com