SlideShare a Scribd company logo
Functional-style programming
HCMC C++ users meetup
Germán Diago Gómez
April 24th, 2016
Germán Diago Gómez Functional-style programming April 24th, 2016 1 / 31
Overview Introduction
Goals of this talk
Introduce some functional-style patterns in C++.
Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
Overview Introduction
Goals of this talk
Introduce some functional-style patterns in C++.
Show some examples combined with the STL.
Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
Overview Introduction
Goals of this talk
Introduce some functional-style patterns in C++.
Show some examples combined with the STL.
Present some more advanced examples of its use at the end.
Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
Overview Introduction
Non-goals
Not a pure-functional Haskell-style programming talk.
Germán Diago Gómez Functional-style programming April 24th, 2016 3 / 31
Functional programming Overview
Main traits
Use of immutable data.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Use of lazy evaluation.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Use of lazy evaluation.
Heavy use of recursivity.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Use of lazy evaluation.
Heavy use of recursivity.
Functions as data. They can be parameters to other functions.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Use of lazy evaluation.
Heavy use of recursivity.
Functions as data. They can be parameters to other functions.
Functions can also be returned.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Main traits
Use of immutable data.
Use of pure functions.
Use of lazy evaluation.
Heavy use of recursivity.
Functions as data. They can be parameters to other functions.
Functions can also be returned.
Composability.
Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
Functional programming Overview
Three important functional algorithms
map → std::transform in STL.
Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
Functional programming Overview
Three important functional algorithms
map → std::transform in STL.
filter → std::remove_if in STL.
Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
Functional programming Overview
Three important functional algorithms
map → std::transform in STL.
filter → std::remove_if in STL.
reduce → std::accumulate in STL.
Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
Functional programming Overview
Three important functional algorithms
map → std::transform in STL.
filter → std::remove_if in STL.
reduce → std::accumulate in STL.
They are the base of many powerful patterns and algorithms.
Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Code much easier to parallelize automatically.
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Code much easier to parallelize automatically.
Higher-order functions enable algorithms customization.
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Code much easier to parallelize automatically.
Higher-order functions enable algorithms customization.
Without rewriting algorithms for special cases.
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Code much easier to parallelize automatically.
Higher-order functions enable algorithms customization.
Without rewriting algorithms for special cases.
Higher order functions enable other useful patterns.
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
Functional programming Overview
Why functional programming
Multithreaded code becomes much easier to deal with (no locks needed).
Code much easier to parallelize automatically.
Higher-order functions enable algorithms customization.
Without rewriting algorithms for special cases.
Higher order functions enable other useful patterns.
Pure functions: can be memoized.
Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
C++ functional style Overview
Main traits
Use of function objects.
Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
C++ functional style Overview
Main traits
Use of function objects.
Use of lambdas.
Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
C++ functional style Overview
Main traits
Use of function objects.
Use of lambdas.
Creating callables that return other callables.
Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
C++ functional style Overview
Main traits
Use of function objects.
Use of lambdas.
Creating callables that return other callables.
Pass function objects/lambdas as parameters, usually to STL algorithms.
Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
C++ functional style Function objects
What is a function object?
A struct or class.
Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
C++ functional style Function objects
What is a function object?
A struct or class.
Implements the call operator operator().
Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
C++ functional style Function objects
What is a function object?
A struct or class.
Implements the call operator operator().
Objects whose class/struct implements operator() can be called the same
way as functions are called.
Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
C++ functional style Function objects
Why function objects are important
The STL makes heavy use of them.
Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
C++ functional style Function objects
Why function objects are important
The STL makes heavy use of them.
Can carry state, unlike classic C style functions.
Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
C++ functional style Function objects
Why function objects are important
The STL makes heavy use of them.
Can carry state, unlike classic C style functions.
Efficient: Easier to inline than function pointers and pointers to members.
Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
C++ functional style Function objects
Why function objects are important
The STL makes heavy use of them.
Can carry state, unlike classic C style functions.
Efficient: Easier to inline than function pointers and pointers to members.
Better code generation.
Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
C++ functional style Function objects
Why function objects are important
The STL makes heavy use of them.
Can carry state, unlike classic C style functions.
Efficient: Easier to inline than function pointers and pointers to members.
Better code generation.
If you understand function objects you understand lambdas.
Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
C++ functional style Function objects
Predicates
A predicate is a callable that returns true or false given some input parameter(s).
Germán Diago Gómez Functional-style programming April 24th, 2016 10 / 31
C++ functional style Function objects
Example (Unary predicate function object)
struct is_negative {
bool operator()(int n) const {
return n < 0;
}
};
std::cout << is_negative{}(-5);
Germán Diago Gómez Functional-style programming April 24th, 2016 11 / 31
C++ functional style Function objects
Example (Unary predicate function object)
struct is_negative {
bool operator()(int n) const {
return n < 0;
}
};
std::cout << is_negative{}(-5);
Output
1
Germán Diago Gómez Functional-style programming April 24th, 2016 11 / 31
C++ functional style Function objects
Example (Binary predicate function object)
struct food {
std::string food_name;
double average_user_score;
};
struct more_delicious {
bool operator()(food const & f1, food const & f2) const {
return f1.average_user_score > f2.average_user_score;
}
};
food const pho{"pho", 8.1}, com_tam{"com tam", 7.6};
std::cout << "Pho more declicious? -> "
<< more_delicious{}(pho, com_tam);
Germán Diago Gómez Functional-style programming April 24th, 2016 12 / 31
C++ functional style Function objects
Example (Binary predicate function object)
struct food {
std::string food_name;
double average_user_score;
};
struct more_delicious {
bool operator()(food const & f1, food const & f2) const {
return f1.average_user_score > f2.average_user_score;
}
};
food const pho{"pho", 8.1}, com_tam{"com tam", 7.6};
std::cout << "Pho more declicious? -> "
<< more_delicious{}(pho, com_tam);
Output
Pho more declicious? -> 1
Germán Diago Gómez Functional-style programming April 24th, 2016 12 / 31
C++ functional style Function objects
Other function objects
Ternary predicates could also exist.
Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
C++ functional style Function objects
Other function objects
Ternary predicates could also exist.
The STL only uses unary and binary.
Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
C++ functional style Function objects
Other function objects
Ternary predicates could also exist.
The STL only uses unary and binary.
Not all function objects are necessarily predicates.
Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
C++ functional style Function objects
Other function objects
Ternary predicates could also exist.
The STL only uses unary and binary.
Not all function objects are necessarily predicates.
Although in the STL predicates are very common in algorithms.
Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
C++ functional style Function objects
(Live demo)
Germán Diago Gómez Functional-style programming April 24th, 2016 14 / 31
C++ functional style Function objects
Problems with function objects
Verbose: must create a class always.
Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
C++ functional style Function objects
Problems with function objects
Verbose: must create a class always.
Usually used once and thrown away.
Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
C++ functional style Function objects
Problems with function objects
Verbose: must create a class always.
Usually used once and thrown away.
Write a class for one use only?
Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
C++ functional style Function objects
Alternatives to handcrafted fuction objects
Use predefined function objects. STL: std::less, std::multiplies and
many others. Insufficient.
Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
C++ functional style Function objects
Alternatives to handcrafted fuction objects
Use predefined function objects. STL: std::less, std::multiplies and
many others. Insufficient.
Compose objects via std::bind. Composing with std::bind is
complicated, less efficient than lambdas and potentially surprising. Avoid.
Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
C++ functional style Function objects
Alternatives to handcrafted fuction objects
Use predefined function objects. STL: std::less, std::multiplies and
many others. Insufficient.
Compose objects via std::bind. Composing with std::bind is
complicated, less efficient than lambdas and potentially surprising. Avoid.
Make use of lambda functions.
Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
C++ functional style Function objects
Alternatives to handcrafted fuction objects
Use predefined function objects. STL: std::less, std::multiplies and
many others. Insufficient.
Compose objects via std::bind. Composing with std::bind is
complicated, less efficient than lambdas and potentially surprising. Avoid.
Make use of lambda functions.
We will focus on lambda functions.
Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
They are equally efficient.
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
They are equally efficient.
Not verbose.
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
They are equally efficient.
Not verbose.
Two kinds in C++
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
They are equally efficient.
Not verbose.
Two kinds in C++
Monomorphic lambdas: non-templated operator().
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Lambda functions
Lambda functions are syntactic sugar for function objects.
They are equally efficient.
Not verbose.
Two kinds in C++
Monomorphic lambdas: non-templated operator().
Polymorphic lambdas: templated operator().
Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
Lambda functions Overview
Anatomy of a lambda function
[capture-list-opt](params) mutable-opt noexcept-opt ->
ret_type { body }.
Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
Lambda functions Overview
Anatomy of a lambda function
[capture-list-opt](params) mutable-opt noexcept-opt ->
ret_type { body }.
The [] is called the lambda introducer.
Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
Lambda functions Overview
Anatomy of a lambda function
[capture-list-opt](params) mutable-opt noexcept-opt ->
ret_type { body }.
The [] is called the lambda introducer.
The capture list is optional.
Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
Lambda functions Overview
Anatomy of a lambda function
[capture-list-opt](params) mutable-opt noexcept-opt ->
ret_type { body }.
The [] is called the lambda introducer.
The capture list is optional.
The ret_type is also optional, otherwise it is deduced from the body.
Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
Lambda functions Overview
Anatomy of a lambda function
[capture-list-opt](params) mutable-opt noexcept-opt ->
ret_type { body }.
The [] is called the lambda introducer.
The capture list is optional.
The ret_type is also optional, otherwise it is deduced from the body.
Lambdas generate by default lambda_class::operator() const.
Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
Lambda functions Overview
Given the following code. . .
std::vector<int> data = {1, 3, 5, 2, 1, 28};
int threshold = 20;
std::partition(std::begin(data), std::end(data), 0,
[threshold](int a)
{ return a < threshold; });
Every lambda function generates a different compiler struct type.
Germán Diago Gómez Functional-style programming April 24th, 2016 19 / 31
Lambda functions Overview
. . . the compiler generates something like this
struct __anon_object {
__anon_object(int _threshold) : //capture variables
threshold(_threshold) {}
decltype(auto) operator(int a, int b) const {
return a < threshold; }
int const threshold; //captured by value
};
std::vector<int> data = {1, 3, 5, 2, 1, 28};
int threshold = 20;
std::partition(std::begin(data), std::end(data), 0,
__anon_object{threshold});
Every lambda generated is unique even if they contain the same code,
captures, etc.
Germán Diago Gómez Functional-style programming April 24th, 2016 20 / 31
Lambda functions Example
Predicates with lambdas
(Demo)
Germán Diago Gómez Functional-style programming April 24th, 2016 21 / 31
Lambda functions Example
Lambdas are very powerful
Can capture the environment (stateful).
Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
Lambda functions Example
Lambdas are very powerful
Can capture the environment (stateful).
They are not verbose as function objects.
Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
Lambda functions Example
Lambdas are very powerful
Can capture the environment (stateful).
They are not verbose as function objects.
Lambdas can save a lot of code but still keep it efficient.
Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
Examples Partial function application
Problem: partial function application
We have a function that renders some text into a target screen with a given size
and orientation.
void render_text(Screen & target, int font_size,
int pos_x, int pos_y,
Orientation text_orientation,
std::string const & text);
We want to call this function all the time with the same parameters to render
different text, but it becomes very tedious: many parameters must be passed.
Germán Diago Gómez Functional-style programming April 24th, 2016 23 / 31
Examples Partial function application
Solution
Screen screen; //Non-copyable
auto render_at_top_left = [=, &screen](std::string const & text) {
return render_text(screen,
80,
k_left_side_screen,
k_top_screen,
Orientation::Horizontal,
text);
};
render_at_top_left("Hello, world!");
Germán Diago Gómez Functional-style programming April 24th, 2016 24 / 31
Examples Measure function wrapper
Problem: timing functions
We want to measure the time it takes to run a function or piece of code and some
functions from some APIs.
We do not have access to the source code of the functions we want to
measure.
Germán Diago Gómez Functional-style programming April 24th, 2016 25 / 31
Examples Measure function wrapper
using namespace std;
template <class Func>
auto timed_func(Func && f) {
return [f = forward<Func>(f)](auto &&... args) {
auto init_time = sc::high_resolution_clock::now();
f(forward<decltype(args)>(args)...);
auto total_exe_time = sc::high_resolution_clock::now()
- init_time;
return sc::duration_cast<sc::milliseconds>
(total_exe_time).count();
};
}
int main() {
vector<int> vec; vec.reserve(2’000’000);
int num = 0;
while (cin >> num) vec.push_back(num);
auto timed_sort = timed_func([&vec]() { sort(begin(vec),
end(vec)); });
Germán Diago Gómez Functional-style programming April 24th, 2016 25 / 31
Examples Map and reduce with STL
cout << "Sorting 2,000,000 numbers took "
<< timed_sort() << " milliseconds.n";
}
Germán Diago Gómez Functional-style programming April 24th, 2016 26 / 31
Examples Map and reduce with STL
Problem: map/reduce data.
Calculate the average of the squares of some series of data
Germán Diago Gómez Functional-style programming April 24th, 2016 26 / 31
Examples Map and reduce with STL
Solution
using namespace std;
vector<int> vec(20);
iota(begin(vec), end(vec), 1);
vector <int> res(20);
transform(std::begin(vec), end(vec), std::begin(res),
[](int val) { return val * val; });
auto total = accumulate(begin(res), end(res), 0,
[](int acc, int val) { return val + acc; });
std::cout << total << ’n’;
Germán Diago Gómez Functional-style programming April 24th, 2016 27 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
This is good because it enables inlining easily. . .
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
This is good because it enables inlining easily. . .
. . . but bad because you cannot store collections of callables or do indirect
calls to them.
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
This is good because it enables inlining easily. . .
. . . but bad because you cannot store collections of callables or do indirect
calls to them.
C++ has function objects, lambdas, pointers to members, function
pointers. . .
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
This is good because it enables inlining easily. . .
. . . but bad because you cannot store collections of callables or do indirect
calls to them.
C++ has function objects, lambdas, pointers to members, function
pointers. . .
With different call syntaxes.
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
Holding any callable
Lambdas and function objects have their own concrete type.
No common class even if can be invoked with same parameters.
This is good because it enables inlining easily. . .
. . . but bad because you cannot store collections of callables or do indirect
calls to them.
C++ has function objects, lambdas, pointers to members, function
pointers. . .
With different call syntaxes.
How can we store arbitrary callables in containers?
Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
Heterogeneus function objects Holding arbitrary callables
std::function<FuncSignature>
std::function can store arbitrary callables.
Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
Heterogeneus function objects Holding arbitrary callables
std::function<FuncSignature>
std::function can store arbitrary callables.
the callables that can store depend on the signature given in its template
parameter.
Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
Heterogeneus function objects Holding arbitrary callables
std::function<FuncSignature>
std::function can store arbitrary callables.
the callables that can store depend on the signature given in its template
parameter.
can capture anything callable: functions, member functions, function objects,
lambdas. . .
Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
Heterogeneus function objects Holding arbitrary callables
std::function use cases
Use when you do not know what you will store until run-time.
Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
Heterogeneus function objects Holding arbitrary callables
std::function use cases
Use when you do not know what you will store until run-time.
Use to store callables in containers. Command pattern is implemented by
std::function directly.
Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
Heterogeneus function objects Holding arbitrary callables
std::function use cases
Use when you do not know what you will store until run-time.
Use to store callables in containers. Command pattern is implemented by
std::function directly.
Prefer auto to std::function when possible for your variables, though.
More efficient.
Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
The end
struct Calculator {
int current_result = 5;
int add_with_context(int a, int b) {
return a + b + current_result;
}
};
int add(int a, int b) { return a + b; }
int main() {
std::function<int (int, int)> bin_op;
bin_op = add; //Store plain function
std::cout << bin_op(3, 5) << std::endl;
Calculator c;
bin_op = std::multiplies<int>{}; //Store function object
std::cout << bin_op(3, 5) << std::endl;
//Call member function capturing calculator object:
bin_op = [&c](int a, int b) { return c.add_with_context(a, b); };
std::cout << bin_op(3, 5) << std::endl;
}
Germán Diago Gómez Functional-style programming April 24th, 2016 31 / 31
The end
Thank you
Germán Diago Gómez Functional-style programming April 24th, 2016 31 / 31

More Related Content

Viewers also liked

ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
zukun
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
Information Technology
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
dgnadt
 
The double lives of spies in the civil war power point
The double lives of spies in the civil war power pointThe double lives of spies in the civil war power point
The double lives of spies in the civil war power point
Alyssa Fabia
 
Windows Server 2008 - Web and Application Hosting
Windows Server 2008 - Web and Application HostingWindows Server 2008 - Web and Application Hosting
Windows Server 2008 - Web and Application Hosting
Information Technology
 

Viewers also liked (20)

Functional programming with python
Functional programming with pythonFunctional programming with python
Functional programming with python
 
CITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHANCITY OF SPIES BY SORAYYA KHAN
CITY OF SPIES BY SORAYYA KHAN
 
ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5ICCV2009: MAP Inference in Discrete Models: Part 5
ICCV2009: MAP Inference in Discrete Models: Part 5
 
SAN Review
SAN ReviewSAN Review
SAN Review
 
Android UI
Android UIAndroid UI
Android UI
 
Lec 03 set
Lec 03   setLec 03   set
Lec 03 set
 
Noah Z - Spies
Noah Z - SpiesNoah Z - Spies
Noah Z - Spies
 
Serial Killers Presentation1
Serial Killers Presentation1Serial Killers Presentation1
Serial Killers Presentation1
 
Scalable Internet Servers and Load Balancing
Scalable Internet Servers and Load BalancingScalable Internet Servers and Load Balancing
Scalable Internet Servers and Load Balancing
 
Intelligence, spies & espionage
Intelligence, spies & espionageIntelligence, spies & espionage
Intelligence, spies & espionage
 
Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012Carrick - Introduction to Physics & Electronics - Spring Review 2012
Carrick - Introduction to Physics & Electronics - Spring Review 2012
 
Trends in spies
Trends in spiesTrends in spies
Trends in spies
 
Lecture#01
Lecture#01Lecture#01
Lecture#01
 
The double lives of spies in the civil war power point
The double lives of spies in the civil war power pointThe double lives of spies in the civil war power point
The double lives of spies in the civil war power point
 
Uni cambridge
Uni cambridgeUni cambridge
Uni cambridge
 
Functional Programming in R
Functional Programming in RFunctional Programming in R
Functional Programming in R
 
Xml Publisher
Xml PublisherXml Publisher
Xml Publisher
 
Windows Server 2008 - Web and Application Hosting
Windows Server 2008 - Web and Application HostingWindows Server 2008 - Web and Application Hosting
Windows Server 2008 - Web and Application Hosting
 
Pertemuan 5_Relation Matriks_01 (17)
Pertemuan 5_Relation Matriks_01 (17)Pertemuan 5_Relation Matriks_01 (17)
Pertemuan 5_Relation Matriks_01 (17)
 
Factories, mocks and spies: a tester's little helpers
Factories, mocks and spies: a tester's little helpersFactories, mocks and spies: a tester's little helpers
Factories, mocks and spies: a tester's little helpers
 

Similar to Functional style programming

Similar to Functional style programming (20)

Stl design overview
Stl design overviewStl design overview
Stl design overview
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
Taming the Legacy Beast: Turning wild old code into a sleak new thoroughbread.
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHP
 
Applied Design Patterns - A Compiler Case Study
Applied Design Patterns - A Compiler Case StudyApplied Design Patterns - A Compiler Case Study
Applied Design Patterns - A Compiler Case Study
 
OODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objectsOODP Unit 1 OOPs classes and objects
OODP Unit 1 OOPs classes and objects
 
Building search and discovery services for Schibsted (LSRS '17)
Building search and discovery services for Schibsted (LSRS '17)Building search and discovery services for Schibsted (LSRS '17)
Building search and discovery services for Schibsted (LSRS '17)
 
Msr2021 tutorial-di penta
Msr2021 tutorial-di pentaMsr2021 tutorial-di penta
Msr2021 tutorial-di penta
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Florentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choiceFlorentin Picioroaga - C++ by choice
Florentin Picioroaga - C++ by choice
 
Practical Experiences Migrating Unified Modeling Language Models to IBM® Rati...
PracticalExperiences Migrating Unified Modeling Language Models to IBM® Rati...PracticalExperiences Migrating Unified Modeling Language Models to IBM® Rati...
Practical Experiences Migrating Unified Modeling Language Models to IBM® Rati...
 
R programming for data science
R programming for data scienceR programming for data science
R programming for data science
 
Reproducible Research in R and R Studio
Reproducible Research in R and R StudioReproducible Research in R and R Studio
Reproducible Research in R and R Studio
 
AnalyticOps - Chicago PAW 2016
AnalyticOps - Chicago PAW 2016AnalyticOps - Chicago PAW 2016
AnalyticOps - Chicago PAW 2016
 
VSSML16 L8. Advanced Workflows: Feature Selection, Boosting, Gradient Descent...
VSSML16 L8. Advanced Workflows: Feature Selection, Boosting, Gradient Descent...VSSML16 L8. Advanced Workflows: Feature Selection, Boosting, Gradient Descent...
VSSML16 L8. Advanced Workflows: Feature Selection, Boosting, Gradient Descent...
 
James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016James Coplien: Trygve - Oct 17, 2016
James Coplien: Trygve - Oct 17, 2016
 
Linux intro 3 grep + Unix piping
Linux intro 3 grep + Unix pipingLinux intro 3 grep + Unix piping
Linux intro 3 grep + Unix piping
 
RESTful Machine Learning with Flask and TensorFlow Serving - Carlo Mazzaferro
RESTful Machine Learning with Flask and TensorFlow Serving - Carlo MazzaferroRESTful Machine Learning with Flask and TensorFlow Serving - Carlo Mazzaferro
RESTful Machine Learning with Flask and TensorFlow Serving - Carlo Mazzaferro
 
ML Best Practices: Prepare Data, Build Models, and Manage Lifecycle (AIM396-S...
ML Best Practices: Prepare Data, Build Models, and Manage Lifecycle (AIM396-S...ML Best Practices: Prepare Data, Build Models, and Manage Lifecycle (AIM396-S...
ML Best Practices: Prepare Data, Build Models, and Manage Lifecycle (AIM396-S...
 
Advanced WhizzML Workflows
Advanced WhizzML WorkflowsAdvanced WhizzML Workflows
Advanced WhizzML Workflows
 

Recently uploaded

How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
Alluxio, Inc.
 

Recently uploaded (20)

How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 

Functional style programming

  • 1. Functional-style programming HCMC C++ users meetup Germán Diago Gómez April 24th, 2016 Germán Diago Gómez Functional-style programming April 24th, 2016 1 / 31
  • 2. Overview Introduction Goals of this talk Introduce some functional-style patterns in C++. Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
  • 3. Overview Introduction Goals of this talk Introduce some functional-style patterns in C++. Show some examples combined with the STL. Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
  • 4. Overview Introduction Goals of this talk Introduce some functional-style patterns in C++. Show some examples combined with the STL. Present some more advanced examples of its use at the end. Germán Diago Gómez Functional-style programming April 24th, 2016 2 / 31
  • 5. Overview Introduction Non-goals Not a pure-functional Haskell-style programming talk. Germán Diago Gómez Functional-style programming April 24th, 2016 3 / 31
  • 6. Functional programming Overview Main traits Use of immutable data. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 7. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 8. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Use of lazy evaluation. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 9. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Use of lazy evaluation. Heavy use of recursivity. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 10. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Use of lazy evaluation. Heavy use of recursivity. Functions as data. They can be parameters to other functions. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 11. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Use of lazy evaluation. Heavy use of recursivity. Functions as data. They can be parameters to other functions. Functions can also be returned. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 12. Functional programming Overview Main traits Use of immutable data. Use of pure functions. Use of lazy evaluation. Heavy use of recursivity. Functions as data. They can be parameters to other functions. Functions can also be returned. Composability. Germán Diago Gómez Functional-style programming April 24th, 2016 4 / 31
  • 13. Functional programming Overview Three important functional algorithms map → std::transform in STL. Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
  • 14. Functional programming Overview Three important functional algorithms map → std::transform in STL. filter → std::remove_if in STL. Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
  • 15. Functional programming Overview Three important functional algorithms map → std::transform in STL. filter → std::remove_if in STL. reduce → std::accumulate in STL. Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
  • 16. Functional programming Overview Three important functional algorithms map → std::transform in STL. filter → std::remove_if in STL. reduce → std::accumulate in STL. They are the base of many powerful patterns and algorithms. Germán Diago Gómez Functional-style programming April 24th, 2016 5 / 31
  • 17. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 18. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Code much easier to parallelize automatically. Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 19. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Code much easier to parallelize automatically. Higher-order functions enable algorithms customization. Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 20. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Code much easier to parallelize automatically. Higher-order functions enable algorithms customization. Without rewriting algorithms for special cases. Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 21. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Code much easier to parallelize automatically. Higher-order functions enable algorithms customization. Without rewriting algorithms for special cases. Higher order functions enable other useful patterns. Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 22. Functional programming Overview Why functional programming Multithreaded code becomes much easier to deal with (no locks needed). Code much easier to parallelize automatically. Higher-order functions enable algorithms customization. Without rewriting algorithms for special cases. Higher order functions enable other useful patterns. Pure functions: can be memoized. Germán Diago Gómez Functional-style programming April 24th, 2016 6 / 31
  • 23. C++ functional style Overview Main traits Use of function objects. Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
  • 24. C++ functional style Overview Main traits Use of function objects. Use of lambdas. Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
  • 25. C++ functional style Overview Main traits Use of function objects. Use of lambdas. Creating callables that return other callables. Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
  • 26. C++ functional style Overview Main traits Use of function objects. Use of lambdas. Creating callables that return other callables. Pass function objects/lambdas as parameters, usually to STL algorithms. Germán Diago Gómez Functional-style programming April 24th, 2016 7 / 31
  • 27. C++ functional style Function objects What is a function object? A struct or class. Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
  • 28. C++ functional style Function objects What is a function object? A struct or class. Implements the call operator operator(). Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
  • 29. C++ functional style Function objects What is a function object? A struct or class. Implements the call operator operator(). Objects whose class/struct implements operator() can be called the same way as functions are called. Germán Diago Gómez Functional-style programming April 24th, 2016 8 / 31
  • 30. C++ functional style Function objects Why function objects are important The STL makes heavy use of them. Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
  • 31. C++ functional style Function objects Why function objects are important The STL makes heavy use of them. Can carry state, unlike classic C style functions. Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
  • 32. C++ functional style Function objects Why function objects are important The STL makes heavy use of them. Can carry state, unlike classic C style functions. Efficient: Easier to inline than function pointers and pointers to members. Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
  • 33. C++ functional style Function objects Why function objects are important The STL makes heavy use of them. Can carry state, unlike classic C style functions. Efficient: Easier to inline than function pointers and pointers to members. Better code generation. Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
  • 34. C++ functional style Function objects Why function objects are important The STL makes heavy use of them. Can carry state, unlike classic C style functions. Efficient: Easier to inline than function pointers and pointers to members. Better code generation. If you understand function objects you understand lambdas. Germán Diago Gómez Functional-style programming April 24th, 2016 9 / 31
  • 35. C++ functional style Function objects Predicates A predicate is a callable that returns true or false given some input parameter(s). Germán Diago Gómez Functional-style programming April 24th, 2016 10 / 31
  • 36. C++ functional style Function objects Example (Unary predicate function object) struct is_negative { bool operator()(int n) const { return n < 0; } }; std::cout << is_negative{}(-5); Germán Diago Gómez Functional-style programming April 24th, 2016 11 / 31
  • 37. C++ functional style Function objects Example (Unary predicate function object) struct is_negative { bool operator()(int n) const { return n < 0; } }; std::cout << is_negative{}(-5); Output 1 Germán Diago Gómez Functional-style programming April 24th, 2016 11 / 31
  • 38. C++ functional style Function objects Example (Binary predicate function object) struct food { std::string food_name; double average_user_score; }; struct more_delicious { bool operator()(food const & f1, food const & f2) const { return f1.average_user_score > f2.average_user_score; } }; food const pho{"pho", 8.1}, com_tam{"com tam", 7.6}; std::cout << "Pho more declicious? -> " << more_delicious{}(pho, com_tam); Germán Diago Gómez Functional-style programming April 24th, 2016 12 / 31
  • 39. C++ functional style Function objects Example (Binary predicate function object) struct food { std::string food_name; double average_user_score; }; struct more_delicious { bool operator()(food const & f1, food const & f2) const { return f1.average_user_score > f2.average_user_score; } }; food const pho{"pho", 8.1}, com_tam{"com tam", 7.6}; std::cout << "Pho more declicious? -> " << more_delicious{}(pho, com_tam); Output Pho more declicious? -> 1 Germán Diago Gómez Functional-style programming April 24th, 2016 12 / 31
  • 40. C++ functional style Function objects Other function objects Ternary predicates could also exist. Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
  • 41. C++ functional style Function objects Other function objects Ternary predicates could also exist. The STL only uses unary and binary. Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
  • 42. C++ functional style Function objects Other function objects Ternary predicates could also exist. The STL only uses unary and binary. Not all function objects are necessarily predicates. Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
  • 43. C++ functional style Function objects Other function objects Ternary predicates could also exist. The STL only uses unary and binary. Not all function objects are necessarily predicates. Although in the STL predicates are very common in algorithms. Germán Diago Gómez Functional-style programming April 24th, 2016 13 / 31
  • 44. C++ functional style Function objects (Live demo) Germán Diago Gómez Functional-style programming April 24th, 2016 14 / 31
  • 45. C++ functional style Function objects Problems with function objects Verbose: must create a class always. Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
  • 46. C++ functional style Function objects Problems with function objects Verbose: must create a class always. Usually used once and thrown away. Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
  • 47. C++ functional style Function objects Problems with function objects Verbose: must create a class always. Usually used once and thrown away. Write a class for one use only? Germán Diago Gómez Functional-style programming April 24th, 2016 15 / 31
  • 48. C++ functional style Function objects Alternatives to handcrafted fuction objects Use predefined function objects. STL: std::less, std::multiplies and many others. Insufficient. Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
  • 49. C++ functional style Function objects Alternatives to handcrafted fuction objects Use predefined function objects. STL: std::less, std::multiplies and many others. Insufficient. Compose objects via std::bind. Composing with std::bind is complicated, less efficient than lambdas and potentially surprising. Avoid. Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
  • 50. C++ functional style Function objects Alternatives to handcrafted fuction objects Use predefined function objects. STL: std::less, std::multiplies and many others. Insufficient. Compose objects via std::bind. Composing with std::bind is complicated, less efficient than lambdas and potentially surprising. Avoid. Make use of lambda functions. Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
  • 51. C++ functional style Function objects Alternatives to handcrafted fuction objects Use predefined function objects. STL: std::less, std::multiplies and many others. Insufficient. Compose objects via std::bind. Composing with std::bind is complicated, less efficient than lambdas and potentially surprising. Avoid. Make use of lambda functions. We will focus on lambda functions. Germán Diago Gómez Functional-style programming April 24th, 2016 16 / 31
  • 52. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 53. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. They are equally efficient. Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 54. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. They are equally efficient. Not verbose. Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 55. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. They are equally efficient. Not verbose. Two kinds in C++ Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 56. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. They are equally efficient. Not verbose. Two kinds in C++ Monomorphic lambdas: non-templated operator(). Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 57. Lambda functions Overview Lambda functions Lambda functions are syntactic sugar for function objects. They are equally efficient. Not verbose. Two kinds in C++ Monomorphic lambdas: non-templated operator(). Polymorphic lambdas: templated operator(). Germán Diago Gómez Functional-style programming April 24th, 2016 17 / 31
  • 58. Lambda functions Overview Anatomy of a lambda function [capture-list-opt](params) mutable-opt noexcept-opt -> ret_type { body }. Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
  • 59. Lambda functions Overview Anatomy of a lambda function [capture-list-opt](params) mutable-opt noexcept-opt -> ret_type { body }. The [] is called the lambda introducer. Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
  • 60. Lambda functions Overview Anatomy of a lambda function [capture-list-opt](params) mutable-opt noexcept-opt -> ret_type { body }. The [] is called the lambda introducer. The capture list is optional. Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
  • 61. Lambda functions Overview Anatomy of a lambda function [capture-list-opt](params) mutable-opt noexcept-opt -> ret_type { body }. The [] is called the lambda introducer. The capture list is optional. The ret_type is also optional, otherwise it is deduced from the body. Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
  • 62. Lambda functions Overview Anatomy of a lambda function [capture-list-opt](params) mutable-opt noexcept-opt -> ret_type { body }. The [] is called the lambda introducer. The capture list is optional. The ret_type is also optional, otherwise it is deduced from the body. Lambdas generate by default lambda_class::operator() const. Germán Diago Gómez Functional-style programming April 24th, 2016 18 / 31
  • 63. Lambda functions Overview Given the following code. . . std::vector<int> data = {1, 3, 5, 2, 1, 28}; int threshold = 20; std::partition(std::begin(data), std::end(data), 0, [threshold](int a) { return a < threshold; }); Every lambda function generates a different compiler struct type. Germán Diago Gómez Functional-style programming April 24th, 2016 19 / 31
  • 64. Lambda functions Overview . . . the compiler generates something like this struct __anon_object { __anon_object(int _threshold) : //capture variables threshold(_threshold) {} decltype(auto) operator(int a, int b) const { return a < threshold; } int const threshold; //captured by value }; std::vector<int> data = {1, 3, 5, 2, 1, 28}; int threshold = 20; std::partition(std::begin(data), std::end(data), 0, __anon_object{threshold}); Every lambda generated is unique even if they contain the same code, captures, etc. Germán Diago Gómez Functional-style programming April 24th, 2016 20 / 31
  • 65. Lambda functions Example Predicates with lambdas (Demo) Germán Diago Gómez Functional-style programming April 24th, 2016 21 / 31
  • 66. Lambda functions Example Lambdas are very powerful Can capture the environment (stateful). Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
  • 67. Lambda functions Example Lambdas are very powerful Can capture the environment (stateful). They are not verbose as function objects. Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
  • 68. Lambda functions Example Lambdas are very powerful Can capture the environment (stateful). They are not verbose as function objects. Lambdas can save a lot of code but still keep it efficient. Germán Diago Gómez Functional-style programming April 24th, 2016 22 / 31
  • 69. Examples Partial function application Problem: partial function application We have a function that renders some text into a target screen with a given size and orientation. void render_text(Screen & target, int font_size, int pos_x, int pos_y, Orientation text_orientation, std::string const & text); We want to call this function all the time with the same parameters to render different text, but it becomes very tedious: many parameters must be passed. Germán Diago Gómez Functional-style programming April 24th, 2016 23 / 31
  • 70. Examples Partial function application Solution Screen screen; //Non-copyable auto render_at_top_left = [=, &screen](std::string const & text) { return render_text(screen, 80, k_left_side_screen, k_top_screen, Orientation::Horizontal, text); }; render_at_top_left("Hello, world!"); Germán Diago Gómez Functional-style programming April 24th, 2016 24 / 31
  • 71. Examples Measure function wrapper Problem: timing functions We want to measure the time it takes to run a function or piece of code and some functions from some APIs. We do not have access to the source code of the functions we want to measure. Germán Diago Gómez Functional-style programming April 24th, 2016 25 / 31
  • 72. Examples Measure function wrapper using namespace std; template <class Func> auto timed_func(Func && f) { return [f = forward<Func>(f)](auto &&... args) { auto init_time = sc::high_resolution_clock::now(); f(forward<decltype(args)>(args)...); auto total_exe_time = sc::high_resolution_clock::now() - init_time; return sc::duration_cast<sc::milliseconds> (total_exe_time).count(); }; } int main() { vector<int> vec; vec.reserve(2’000’000); int num = 0; while (cin >> num) vec.push_back(num); auto timed_sort = timed_func([&vec]() { sort(begin(vec), end(vec)); }); Germán Diago Gómez Functional-style programming April 24th, 2016 25 / 31
  • 73. Examples Map and reduce with STL cout << "Sorting 2,000,000 numbers took " << timed_sort() << " milliseconds.n"; } Germán Diago Gómez Functional-style programming April 24th, 2016 26 / 31
  • 74. Examples Map and reduce with STL Problem: map/reduce data. Calculate the average of the squares of some series of data Germán Diago Gómez Functional-style programming April 24th, 2016 26 / 31
  • 75. Examples Map and reduce with STL Solution using namespace std; vector<int> vec(20); iota(begin(vec), end(vec), 1); vector <int> res(20); transform(std::begin(vec), end(vec), std::begin(res), [](int val) { return val * val; }); auto total = accumulate(begin(res), end(res), 0, [](int acc, int val) { return val + acc; }); std::cout << total << ’n’; Germán Diago Gómez Functional-style programming April 24th, 2016 27 / 31
  • 76. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 77. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 78. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. This is good because it enables inlining easily. . . Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 79. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. This is good because it enables inlining easily. . . . . . but bad because you cannot store collections of callables or do indirect calls to them. Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 80. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. This is good because it enables inlining easily. . . . . . but bad because you cannot store collections of callables or do indirect calls to them. C++ has function objects, lambdas, pointers to members, function pointers. . . Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 81. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. This is good because it enables inlining easily. . . . . . but bad because you cannot store collections of callables or do indirect calls to them. C++ has function objects, lambdas, pointers to members, function pointers. . . With different call syntaxes. Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 82. Heterogeneus function objects Holding arbitrary callables Holding any callable Lambdas and function objects have their own concrete type. No common class even if can be invoked with same parameters. This is good because it enables inlining easily. . . . . . but bad because you cannot store collections of callables or do indirect calls to them. C++ has function objects, lambdas, pointers to members, function pointers. . . With different call syntaxes. How can we store arbitrary callables in containers? Germán Diago Gómez Functional-style programming April 24th, 2016 28 / 31
  • 83. Heterogeneus function objects Holding arbitrary callables std::function<FuncSignature> std::function can store arbitrary callables. Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
  • 84. Heterogeneus function objects Holding arbitrary callables std::function<FuncSignature> std::function can store arbitrary callables. the callables that can store depend on the signature given in its template parameter. Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
  • 85. Heterogeneus function objects Holding arbitrary callables std::function<FuncSignature> std::function can store arbitrary callables. the callables that can store depend on the signature given in its template parameter. can capture anything callable: functions, member functions, function objects, lambdas. . . Germán Diago Gómez Functional-style programming April 24th, 2016 29 / 31
  • 86. Heterogeneus function objects Holding arbitrary callables std::function use cases Use when you do not know what you will store until run-time. Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
  • 87. Heterogeneus function objects Holding arbitrary callables std::function use cases Use when you do not know what you will store until run-time. Use to store callables in containers. Command pattern is implemented by std::function directly. Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
  • 88. Heterogeneus function objects Holding arbitrary callables std::function use cases Use when you do not know what you will store until run-time. Use to store callables in containers. Command pattern is implemented by std::function directly. Prefer auto to std::function when possible for your variables, though. More efficient. Germán Diago Gómez Functional-style programming April 24th, 2016 30 / 31
  • 89. The end struct Calculator { int current_result = 5; int add_with_context(int a, int b) { return a + b + current_result; } }; int add(int a, int b) { return a + b; } int main() { std::function<int (int, int)> bin_op; bin_op = add; //Store plain function std::cout << bin_op(3, 5) << std::endl; Calculator c; bin_op = std::multiplies<int>{}; //Store function object std::cout << bin_op(3, 5) << std::endl; //Call member function capturing calculator object: bin_op = [&c](int a, int b) { return c.add_with_context(a, b); }; std::cout << bin_op(3, 5) << std::endl; } Germán Diago Gómez Functional-style programming April 24th, 2016 31 / 31
  • 90. The end Thank you Germán Diago Gómez Functional-style programming April 24th, 2016 31 / 31