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)

PPTX
Chp7_C++_Functions_Part1_Built-in functions.pptx
ssuser10ed71
 
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
PPTX
FunctionalJS - George Shevtsov
Georgiy Shevtsov
 
PPTX
1. George Shevtsov - Functional JavaScript
Innovecs
 
PDF
Refactoring to Macros with Clojure
Dmitry Buzdin
 
PDF
Functional programming in ruby
Koen Handekyn
 
PPTX
Things about Functional JavaScript
ChengHui Weng
 
PDF
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Fwdays
 
PDF
Compact and safely: static DSL on Kotlin
Dmitry Pranchuk
 
PDF
Emerging Languages: A Tour of the Horizon
Alex Payne
 
PPT
Matlab1
guest8ba004
 
PPT
Python 101 language features and functional programming
Lukasz Dynowski
 
PDF
From Javascript To Haskell
ujihisa
 
ODP
Patterns for slick database applications
Skills Matter
 
PPTX
Mbd2
Mahmoud Hussein
 
PPS
CS101- Introduction to Computing- Lecture 35
Bilal Ahmed
 
PPTX
EcmaScript unchained
Eduard Tomàs
 
PPTX
C++ process new
敬倫 林
 
PPSX
Scala @ TomTom
Eric Bowman
 
Chp7_C++_Functions_Part1_Built-in functions.pptx
ssuser10ed71
 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
FunctionalJS - George Shevtsov
Georgiy Shevtsov
 
1. George Shevtsov - Functional JavaScript
Innovecs
 
Refactoring to Macros with Clojure
Dmitry Buzdin
 
Functional programming in ruby
Koen Handekyn
 
Things about Functional JavaScript
ChengHui Weng
 
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Fwdays
 
Compact and safely: static DSL on Kotlin
Dmitry Pranchuk
 
Emerging Languages: A Tour of the Horizon
Alex Payne
 
Matlab1
guest8ba004
 
Python 101 language features and functional programming
Lukasz Dynowski
 
From Javascript To Haskell
ujihisa
 
Patterns for slick database applications
Skills Matter
 
CS101- Introduction to Computing- Lecture 35
Bilal Ahmed
 
EcmaScript unchained
Eduard Tomàs
 
C++ process new
敬倫 林
 
Scala @ TomTom
Eric Bowman
 
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
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PPTX
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
PDF
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
PPTX
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
PPTX
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
DOCX
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
PDF
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PPTX
arctitecture application system design os dsa
za241967
 
PDF
Mastering VPC Architecture Build for Scale from Day 1.pdf
Devseccops.ai
 
PDF
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
PDF
Automated Test Case Repair Using Language Models
Lionel Briand
 
PPTX
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PDF
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
PDF
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
PPTX
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
PDF
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
PDF
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
ERP Systems in the UAE: Driving Business Transformation with Smart Solutions
dheeodoo
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
Alur Perkembangan Software dan Jaringan Komputer
ssuser754303
 
Avast Premium Security crack 25.5.6162 + License Key 2025
HyperPc soft
 
Threat Modeling a Batch Job Framework - Teri Radichel - AWS re:Inforce 2025
2nd Sight Lab
 
Best AI-Powered Wearable Tech for Remote Health Monitoring in 2025
SEOLIFT - SEO Company London
 
Automated Testing and Safety Analysis of Deep Neural Networks
Lionel Briand
 
Rewards and Recognition (2).pdf
ethan Talor
 
arctitecture application system design os dsa
za241967
 
Mastering VPC Architecture Build for Scale from Day 1.pdf
Devseccops.ai
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Automated Test Case Repair Using Language Models
Lionel Briand
 
IObit Driver Booster Pro 12 Crack Latest Version Download
pcprocore
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Why Edge Computing Matters in Mobile Application Tech.pdf
IMG Global Infotech
 
IDM Crack with Internet Download Manager 6.42 [Latest 2025]
HyperPc soft
 
Azure AI Foundry: The AI app and agent factory
Maxim Salnikov
 
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 

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]