SlideShare a Scribd company logo
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 (20)

PPT
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
PDF
Futures e abstração - QCon São Paulo 2015
Leonardo Borges
 
PDF
Compose Async with RxJS
Kyung Yeol Kim
 
PDF
Functional "Life": parallel cellular automata and comonads
Alexander Granin
 
PDF
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
PDF
Polymorphism
mohamed sikander
 
PDF
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
PDF
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
DOC
Ds 2 cycle
Chaitanya Kn
 
PDF
Дмитрий Верескун «Синтаксический сахар C#»
SpbDotNet Community
 
PDF
Bind me if you can
Ovidiu Farauanu
 
PDF
Extend R with Rcpp!!!
mickey24
 
PDF
Container adapters
mohamed sikander
 
PDF
C programs
Vikram Nandini
 
PDF
Coding in Style
scalaconfjp
 
PPTX
Chapter 7 functions (c)
hhliu
 
PDF
C program
Komal Singh
 
PPT
Advance features of C++
vidyamittal
 
PPT
C++totural file
halaisumit
 
DOCX
Data Structure Project File
Deyvessh kumar
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
Futures e abstração - QCon São Paulo 2015
Leonardo Borges
 
Compose Async with RxJS
Kyung Yeol Kim
 
Functional "Life": parallel cellular automata and comonads
Alexander Granin
 
The Ring programming language version 1.3 book - Part 84 of 88
Mahmoud Samir Fayed
 
Polymorphism
mohamed sikander
 
Yurii Shevtsov "V8 + libuv = Node.js. Under the hood"
OdessaJS Conf
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
Ds 2 cycle
Chaitanya Kn
 
Дмитрий Верескун «Синтаксический сахар C#»
SpbDotNet Community
 
Bind me if you can
Ovidiu Farauanu
 
Extend R with Rcpp!!!
mickey24
 
Container adapters
mohamed sikander
 
C programs
Vikram Nandini
 
Coding in Style
scalaconfjp
 
Chapter 7 functions (c)
hhliu
 
C program
Komal Singh
 
Advance features of C++
vidyamittal
 
C++totural file
halaisumit
 
Data Structure Project File
Deyvessh kumar
 

Viewers also liked (20)

PDF
Coding Dojo: Fun with Tic-Tac-Toe (2014)
Peter Kofler
 
PPTX
Serial Killers Psychology Presentation
Pietro Solda
 
PDF
Android Basic Components
Jussi Pohjolainen
 
PPT
Network Security and Cryptography
Adam Reagan
 
PDF
Introduction to Functional Programming with Scala
pramode_ce
 
PPTX
Functional programming
Olga Lavrentieva
 
PPTX
15 10-22 altoros-fact_sheet_st_v4
Olga Lavrentieva
 
PPT
SAN Review
Information Technology
 
PPTX
Carrick - Introduction to Physics & Electronics - Spring Review 2012
The Air Force Office of Scientific Research
 
PPTX
Functional programming with python
Marcelo Cure
 
PPT
Securing Windows web servers
Information Technology
 
PPTX
Noah Z - Spies
Mrs. Haglin
 
PPTX
Trends in spies
Trend Reportz
 
PPTX
Intelligence, spies & espionage
dgnadt
 
PPT
Lec 03 set
Naosher Md. Zakariyar
 
PDF
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 
PDF
Functional style programming
Germán Diago Gómez
 
PDF
Android UI
Sven Haiges
 
PPTX
CITY OF SPIES BY SORAYYA KHAN
Sheikh Hasnain
 
Coding Dojo: Fun with Tic-Tac-Toe (2014)
Peter Kofler
 
Serial Killers Psychology Presentation
Pietro Solda
 
Android Basic Components
Jussi Pohjolainen
 
Network Security and Cryptography
Adam Reagan
 
Introduction to Functional Programming with Scala
pramode_ce
 
Functional programming
Olga Lavrentieva
 
15 10-22 altoros-fact_sheet_st_v4
Olga Lavrentieva
 
Carrick - Introduction to Physics & Electronics - Spring Review 2012
The Air Force Office of Scientific Research
 
Functional programming with python
Marcelo Cure
 
Securing Windows web servers
Information Technology
 
Noah Z - Spies
Mrs. Haglin
 
Trends in spies
Trend Reportz
 
Intelligence, spies & espionage
dgnadt
 
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 
Functional style programming
Germán Diago Gómez
 
Android UI
Sven Haiges
 
CITY OF SPIES BY SORAYYA KHAN
Sheikh Hasnain
 
Ad

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

PDF
Functional programming in C++
Alexandru Bolboaca
 
PDF
The present and the future of functional programming in c++
Alexander Granin
 
PDF
The Present and The Future of Functional Programming in C++
Alexander Granin
 
PDF
A taste of Functional Programming
Jordan Open Source Association
 
PPTX
Good functional programming is good programming
kenbot
 
PDF
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
PDF
Thinking in Functions
Alexandru Bolboaca
 
PDF
A (very brief) into to Functional Programming
Brooklyn Zelenka
 
PPTX
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
PPS
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
PPTX
Functional Paradigm.pptx
FurretMaster
 
PDF
Why you should care about functional programming
Dhananjay Nene
 
PPT
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
PPT
Functional Programming Past Present Future
IndicThreads
 
PPTX
The joy of functional programming
Steve Zhang
 
PPTX
Functional Programming Concepts for Imperative Programmers
Chris
 
PPTX
Can programming be liberated from the von neumann style?
Oriol López Massaguer
 
PDF
Data Structure and Algorithm
PRIYA DARSHINI A/P VEJAN
 
PPTX
Why functional programming in C# & F#
Riccardo Terrell
 
PPTX
Functional pogramming hl overview
Elad Avneri
 
Functional programming in C++
Alexandru Bolboaca
 
The present and the future of functional programming in c++
Alexander Granin
 
The Present and The Future of Functional Programming in C++
Alexander Granin
 
A taste of Functional Programming
Jordan Open Source Association
 
Good functional programming is good programming
kenbot
 
Introduction to functional programming (In Arabic)
Omar Abdelhafith
 
Thinking in Functions
Alexandru Bolboaca
 
A (very brief) into to Functional Programming
Brooklyn Zelenka
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Sigma Software
 
Presentation of GetTogether on Functional Programming
Filip De Sutter
 
Functional Paradigm.pptx
FurretMaster
 
Why you should care about functional programming
Dhananjay Nene
 
Functional Programming - Past, Present and Future
Pushkar Kulkarni
 
Functional Programming Past Present Future
IndicThreads
 
The joy of functional programming
Steve Zhang
 
Functional Programming Concepts for Imperative Programmers
Chris
 
Can programming be liberated from the von neumann style?
Oriol López Massaguer
 
Data Structure and Algorithm
PRIYA DARSHINI A/P VEJAN
 
Why functional programming in C# & F#
Riccardo Terrell
 
Functional pogramming hl overview
Elad Avneri
 
Ad

More from Platonov Sergey (20)

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

Recently uploaded (20)

PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PPTX
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Platform for Enterprise Solution - Java EE5
abhishekoza1981
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
A Complete Guide to Salesforce SMS Integrations Build Scalable Messaging With...
360 SMS APP
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Executive Business Intelligence Dashboards
vandeslie24
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
3uTools Full Crack Free Version Download [Latest] 2025
muhammadgurbazkhan
 

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 [email protected]