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

PDF
Bartosz Milewski, “Re-discovering Monads in C++”
PDF
Functional microscope - Lenses in C++
PPTX
Operator overloading2
PDF
Java8 stream
PDF
Dynamic C++ ACCU 2013
PDF
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
PPTX
PVS-Studio team experience: checking various open source projects, or mistake...
Bartosz Milewski, “Re-discovering Monads in C++”
Functional microscope - Lenses in C++
Operator overloading2
Java8 stream
Dynamic C++ ACCU 2013
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
PVS-Studio team experience: checking various open source projects, or mistake...

What's hot (20)

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

Viewers also liked (20)

PDF
Coding Dojo: Fun with Tic-Tac-Toe (2014)
PPTX
Serial Killers Psychology Presentation
PDF
Android Basic Components
PPT
Network Security and Cryptography
PDF
Introduction to Functional Programming with Scala
PPTX
Functional programming
PPTX
15 10-22 altoros-fact_sheet_st_v4
PPT
PPTX
Carrick - Introduction to Physics & Electronics - Spring Review 2012
PPTX
Functional programming with python
PPT
Securing Windows web servers
PPTX
Noah Z - Spies
PPTX
Trends in spies
PPTX
Intelligence, spies & espionage
PPT
PDF
ICCV2009: MAP Inference in Discrete Models: Part 5
PDF
Functional style programming
PDF
Android UI
PPTX
CITY OF SPIES BY SORAYYA KHAN
Coding Dojo: Fun with Tic-Tac-Toe (2014)
Serial Killers Psychology Presentation
Android Basic Components
Network Security and Cryptography
Introduction to Functional Programming with Scala
Functional programming
15 10-22 altoros-fact_sheet_st_v4
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Functional programming with python
Securing Windows web servers
Noah Z - Spies
Trends in spies
Intelligence, spies & espionage
ICCV2009: MAP Inference in Discrete Models: Part 5
Functional style programming
Android UI
CITY OF SPIES BY SORAYYA KHAN
Ad

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

PPTX
Chp7_C++_Functions_Part1_Built-in functions.pptx
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
PPTX
FunctionalJS - George Shevtsov
PPTX
1. George Shevtsov - Functional JavaScript
PDF
Refactoring to Macros with Clojure
PDF
Functional programming in ruby
PPTX
Things about Functional JavaScript
PDF
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
PDF
Compact and safely: static DSL on Kotlin
PDF
Emerging Languages: A Tour of the Horizon
PPT
Matlab1
PPT
Python 101 language features and functional programming
PDF
From Javascript To Haskell
ODP
Patterns for slick database applications
PPTX
PPS
CS101- Introduction to Computing- Lecture 35
PPTX
EcmaScript unchained
PPTX
C++ process new
PPSX
Scala @ TomTom
Chp7_C++_Functions_Part1_Built-in functions.pptx
Design Patterns - Compiler Case Study - Hands-on Examples
FunctionalJS - George Shevtsov
1. George Shevtsov - Functional JavaScript
Refactoring to Macros with Clojure
Functional programming in ruby
Things about Functional JavaScript
"Optimization of a .NET application- is it simple ! / ?", Yevhen Tatarynov
Compact and safely: static DSL on Kotlin
Emerging Languages: A Tour of the Horizon
Matlab1
Python 101 language features and functional programming
From Javascript To Haskell
Patterns for slick database applications
CS101- Introduction to Computing- Lecture 35
EcmaScript unchained
C++ process new
Scala @ TomTom

More from Platonov Sergey (20)

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

Recently uploaded (20)

PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Nekopoi APK 2025 free lastest update
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
top salesforce developer skills in 2025.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Digital Strategies for Manufacturing Companies
PPTX
Online Work Permit System for Fast Permit Processing
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
L1 - Introduction to python Backend.pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Odoo POS Development Services by CandidRoot Solutions
VVF-Customer-Presentation2025-Ver1.9.pptx
How to Migrate SBCGlobal Email to Yahoo Easily
How to Choose the Right IT Partner for Your Business in Malaysia
Nekopoi APK 2025 free lastest update
Operating system designcfffgfgggggggvggggggggg
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
top salesforce developer skills in 2025.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Wondershare Filmora 15 Crack With Activation Key [2025
Digital Strategies for Manufacturing Companies
Online Work Permit System for Fast Permit Processing
CHAPTER 2 - PM Management and IT Context
Design an Analysis of Algorithms I-SECS-1021-03
Navsoft: AI-Powered Business Solutions & Custom Software Development
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
L1 - Introduction to python Backend.pptx
Design an Analysis of Algorithms II-SECS-1021-03
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025

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