SlideShare a Scribd company logo
The beast is becoming functional
CoreHard, Minsk 2017
Ivan Čukić
ivan.cukic@kde.org
http://cukic.co
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Disclaimer
Make your code readable. Pretend the next person
who looks at your code is a psychopath and they
know where you live.
Philip Wadler
2
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Connections
3
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Functional programming
Higher-order functions
Algebraic data types
Purity
Laziness
etc.
4
THE MIRACLE OF BIRTH
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
#include <functional>
#include <algorithm>
6
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
7
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
7
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
template <typename It, typename Predicate>
std::pair<It, It>
move_selection(It first, It last,
It destination,
Pred predicate)
{
return std::make_pair(
std::stable_partition(first, destination,
negate(predicate));
std::stable_partition(destination, last,
predicate)
);
}
8
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
operator() + templates
9
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
std::multiplies<float>()
std::bind1st(⋯)
arg1 * arg2 boost.phoenix
10
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine that Goes ”Ping”
std::multiplies<>()
std::bind(⋯)
arg1 * arg2 boost.phoenix
11
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Machine Stopped
Problems:
One-off functions
Problems with iterators
Problem with tuples
12
GROWTH AND LEARNING
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Lambdas
Lambdas – syntactic sugar for creating function objects:
std::stable_partition(
first, destination,
[&] (auto&& value) {
return !predicate(FWD(value));
});
// FWD - std::forward<decltype(value)>(value)
14
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Algorithm composition
15
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Algorithm composition
people.erase(
std::remove_if(people.begin(), people.end(),
is_not_female),
people.end());
// or std::copy_if
std::transform(people.begin(), people.end(),
std::back_inserer(names),
&person::name);
16
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Algorithm composition
Ranges to the rescue:
people | filter(is_female)
| transform(&person::name);
17
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Algorithm composition
auto mistery_function(vector<gadget> gadgets, int offset, int count)
{
vector<gadget> result;
int skipped = 0, took = 0;
for (const auto &gadget: gadgets) {
if (is_container(gadget))
continue;
vector<gadget> children;
for (const auto &child: children(gadget)) {
if (is_visible(child)) {
if (skipped < offset) {
skipped++;
} else if (took <= count) {
took++;
children.push_back(child);
}
}
}
copy(children.cbegin(), children.cend(), back_inserter(result));
}
return result;
}
18
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Algorithm composition
auto mistery_function(vector<gadget> gadgets,
int offset, int count)
{
return gadgets | filtered(is_container)
| transformed(children)
| flatten()
| filtered(is_visible)
| drop(offset)
| take(count);
}
19
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Meaning of Tuples
template <typename It, typename Predicate>
std::pair<It, It>
move_selection(It first, It last,
It destination,
Pred predicate)
{
⋯
}
20
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Meaning of Tuples
auto selection = move_selection(⋯);
std::sort(selection.first, selection.second);
21
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
The Meaning of Tuples
auto [ selected_begin, selected_end ] =
move_selection(⋯);
std::sort(selected_begin, selected_end);
22
FIGHTING EACH OTHER
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
Problem:
Create a program that fetches a web page
and counts the words in that page
24
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
States:
The initial state
The counting state
The final state
25
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
struct state_t {
bool started = false;
bool finished = false;
unsigned count = 0; not needed until started
string url;
socket_t web_page;
};
26
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
struct state_t {
bool started = false;
bool finished = false;
unsigned count = 0;
string url; not needed after started
socket_t web_page;
};
26
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
struct state_t {
bool started = false;
bool finished = false;
unsigned count = 0;
string url;
socket_t web_page; needed only while working
};
26
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Word counting
struct state_t {
bool started = false;
bool finished = true;
unsigned count = 42;
string url = ”http://isocpp.org”;
socket_t web_page = ⋯;
};
27
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Fighting each other
28
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types
A sum of types A and B is a type that contains an instance of
A or an instance of B, but not both at the same time.
A ∪ B
29
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
We can implement sum types through inheritance.
Create a state_t super-class, and sub-classes for each of
the states.
30
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class state_t {
protected:
state_t(int type) we can not create instances
: type(type) of this type directly
{
}
public:
const int type;
virtual ~state_t() {};
};
31
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class init_t: public state_t {
public:
enum { id = 0 };
init_t()
: state_t(id)
{
}
string url;
};
32
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class running_t: public state_t {
public:
enum { id = 1 };
init_t()
: state_t(id)
{
}
unsigned m_count = 0;
socket_t m_web_page;
};
33
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class finished_t: public state_t {
public:
enum { id = 2 };
init_t()
: state_t(id)
{
}
const unsigned m_count = 0;
};
34
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
35
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class program_t {
public:
program_t() The initial
: m_state(make_unique<init_t>()) program state
{
}
void counting_finished()
{
assert(m_state->type == running_t::id);
auto state =
static_cast<running_t*>(m_state.get());
m_state.reset(
make_unique<finished_t>(state->m_count));
}
private:
unique_ptr<state_t> m_state;
};
36
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class program_t {
public:
program_t()
: m_state(make_unique<init_t>())
{
}
void counting_finished()
{
assert(m_state->type == running_t::id); We must have been running
auto state = in order for this function
static_cast<running_t*>(m_state.get()); to be called
m_state.reset(
make_unique<finished_t>(state->m_count));
}
private:
unique_ptr<state_t> m_state;
};
36
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
class program_t {
public:
program_t()
: m_state(make_unique<init_t>())
{
}
void counting_finished()
{
assert(m_state->type == running_t::id);
auto state =
static_cast<running_t*>(m_state.get());
m_state.reset(
make_unique<finished_t>(state->m_count)); Changing state
}
private:
unique_ptr<state_t> m_state;
};
36
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Sum types using inheritance
We can have no invalid states
Set of states is easily extendable (open sum types)
Automatic resource disposal for resources tied to a
particular state
Bad: A lot of boilerplate
37
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
38
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
struct init_t { string url; };
struct running_t {
unsigned m_count;
socket_t m_web_page;
};
struct finished_t {
const unsigned m_count;
}
std::variant < init_t We can just list all
, running_t the types that we want
, finished_t to use for state handling
> m_state;
39
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
void counting_finished()
{
auto *state = get_if<running_t>(&m_state);
assert(state != nullptr);
m_state = finished_t(state->m_count);
}
40
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
We can have no invalid states
Set of states is fixed (closed sum types)
Automatic resource disposal for resources tied to a
particular state
No boilerplate
41
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
std::visit(
[] (const auto& value) {
std::cout << value << std::endl;
}, m_state);
42
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Type-safe unions
template <typename... Ts>
struct overloaded: Ts... { using Ts::operator()...; };
std::visit(overloaded {
[&] (const init_t& state) {
⋯
},
[&] (const running_t& state) {
⋯
},
[&] (const finished_t& state) {
⋯
}
}, m_state);
43
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Optional values
std::optional<T> – a sum type of T and nothing
struct nothing_t {};
template <typename T>
using optional = variant<nothing_t, T>;
But with a nicer API.
44
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Optional values
When we have optional arguments
When a function can fail
...
45
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Optional values
template <typename T, typename Variant>
optional<T> get_if(const Variant& variant)
{
T* ptr = std::get_if<T>(&variant);
if (ptr) {
return *ptr;
} else {
return optional<T>();
}
}
46
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
The optional does not keep information about the error.
template<typename T, typename E = std::exception_ptr>
class expected {
public:
// ⋯
private:
union {
T m_value;
E m_error;
};
bool m_valid;
};
47
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
template<typename T, typename E = std::exception_ptr>
class expected {
public:
const T& get() const
{
if (!m_valid) {
throw logic_error(”Missing a value”);
}
return m_value;
}
// ⋯
private:
// ⋯
};
48
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
template<typename T, typename E = std::exception_ptr>
class expected {
public:
template <typename... ConsParams>
static expected success(ConsParams&& ...params)
{
expected result;
result.m_valid = true;
new (&result.m_value)
T(forward<ConsParams>(params)...);
return result;
}
// ⋯
private:
// ⋯
};
49
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
template<typename T, typename E = std::exception_ptr>
class expected {
public:
~expected()
{
if (m_valid) {
m_value.~T();
} else {
m_error.~E();
}
}
// ⋯
private:
// ⋯
};
50
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
template<typename T, typename E = std::exception_ptr>
class expected {
public:
expected(const expected& other)
: m_valid(other.m_valid)
{
if (m_valid) {
new (&m_value) T(other.m_value);
} else {
new (&m_error) E(other.m_error);
}
}
// ⋯
private:
// ⋯
};
51
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
public:
void swap(expected& other)
{
using std::swap;
if (m_valid) {
if (other.m_valid) {
swap(m_value, other.m_value);
} else {
auto temp = std::move(other.m_error);
other.m_error.~E();
new (&other.m_value) T(std::move(m_value));
m_value.~T();
new (&m_error) E(std::move(temp));
std::swap(m_valid, other.m_valid);
}
} else {
// ⋯
52
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Error handling
public:
void swap(expected& other)
{
using std::swap;
if (m_valid) {
// ⋯
} else {
if (other.m_valid) {
other.swap(*this);
} else {
swap(m_error, other.m_error);
}
}
}
};
53
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling optional and expected values
optional<string> login = current_user();
if (!user) return error
optional<user_t> user = get_info(login.get());
if (!user) return error
optional<string> full_name =
get_full_name(user.get());
if (full_name) return error
⋯
54
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling optional and expected values
Optional (and expected) values are like containers with at
most one element.
55
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling optional and expected values
current_user: () -> optional<string>
get_info: string -> optional<user_t>
get_full_name: user_t -> optional<string>
current_user()
| transform(get_info)
| transform(get_full_name)
| ⋯
;
56
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling optional and expected values
current_user: () -> optional<string>
get_info: string -> optional<user_t>
get_full_name: user_t -> optional<string>
current_user()
| mbind(get_info)
| mbind(get_full_name)
| ⋯
;
57
THE AUTUMN YEARS
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling future values
Future values are like containers that will get the value
later.
59
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling future values
current_user: () -> future<string>
get_info: string -> future<user_t>
get_full_name: user_t -> future<string>
current_user()
| mbind(get_info)
| mbind(get_full_name)
| ⋯
;
60
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Handling future values
current_user: () -> future<string>
get_info: string -> future<user_t>
get_full_name: user_t -> future<string>
current_user()
.then(get_info)
.then(get_full_name)
⋯
;
61
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Imperative on top
current_user: () -> future<string>
get_info: string -> future<user_t>
get_full_name: user_t -> future<string>
auto user = co_await current_user();
auto info = co_await get_info(user);
auto name = co_await get_full_name(info);
62
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Imperative on top
co_await expression is equivalent to:
{
auto && tmp = <expr>;
if (!await_ready(tmp)) {
await_suspend(tmp, continuation);
}
return await_resume(tmp);
}
63
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Imperative on top
A core-language feature to implement .then
64
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Imperative on top
A core-language feature to implement mbind
64
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Imperative on top
current_user: () -> optional<string>
get_info: string -> optional<user_t>
get_full_name: user_t -> optional<string>
auto user = co_await current_user();
auto info = co_await get_info(user);
auto name = co_await get_full_name(info);
65
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Summary
First, higher-order functions
Then, alternative type design safe state handling with
sum types
Combination of the two
Monadic design
Finally baking the monad into the core-language
66
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Compilation process
Write imperative co_await-based code
Converted to functional (monadic) design
Uses TMP for the type
Unwraps all into imperative code
Converted to a single-assignment internal compiler
language
To be finally converted to assembly
67
The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard
Answers? Questions! Questions? Answers!
Kudos (in chronological order):
Friends at KDE
Saša Malkov and Zoltan Porkolab
Антон Наумович and Сергей Платонов
MEAP – Manning Early Access Program
Functional Programming in C++
cukic.co/to/fp-in-cpp
Discount code (40% off all Manning books):
ctwcorehard
68

More Related Content

Viewers also liked

Abseil - let the savior come?
Abseil - let the savior come?Abseil - let the savior come?
Abseil - let the savior come?
corehard_by
 
C++Now Trip Report
C++Now Trip ReportC++Now Trip Report
C++Now Trip Report
corehard_by
 
Поиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кодаПоиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кода
corehard_by
 
Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11
corehard_by
 
C++ в играх, больших и не очень
C++ в играх, больших и не оченьC++ в играх, больших и не очень
C++ в играх, больших и не очень
corehard_by
 
MxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency ManagerMxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency Manager
corehard_by
 
Analysis and interpretation of monitoring data
Analysis and interpretation of monitoring dataAnalysis and interpretation of monitoring data
Analysis and interpretation of monitoring data
corehard_by
 
Ускоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборокУскоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборок
corehard_by
 
Restinio - header-only http and websocket server
Restinio - header-only http and websocket serverRestinio - header-only http and websocket server
Restinio - header-only http and websocket server
corehard_by
 
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Ontico
 
Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?
COMAQA.BY
 
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Ontico
 
Развитие или смерть
Развитие или смертьРазвитие или смерть
Развитие или смерть
COMAQA.BY
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines
Sergey Zubkov
 

Viewers also liked (14)

Abseil - let the savior come?
Abseil - let the savior come?Abseil - let the savior come?
Abseil - let the savior come?
 
C++Now Trip Report
C++Now Trip ReportC++Now Trip Report
C++Now Trip Report
 
Поиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кодаПоиск уязвимостей с использованием статического анализа кода
Поиск уязвимостей с использованием статического анализа кода
 
Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11Mixing C++ & Python II: Pybind11
Mixing C++ & Python II: Pybind11
 
C++ в играх, больших и не очень
C++ в играх, больших и не оченьC++ в играх, больших и не очень
C++ в играх, больших и не очень
 
MxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency ManagerMxxRu::externals: Repositoryless Dependency Manager
MxxRu::externals: Repositoryless Dependency Manager
 
Analysis and interpretation of monitoring data
Analysis and interpretation of monitoring dataAnalysis and interpretation of monitoring data
Analysis and interpretation of monitoring data
 
Ускоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборокУскоряем сборку С++ проектов. Практика использования unity-сборок
Ускоряем сборку С++ проектов. Практика использования unity-сборок
 
Restinio - header-only http and websocket server
Restinio - header-only http and websocket serverRestinio - header-only http and websocket server
Restinio - header-only http and websocket server
 
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
Метаданные для кластера: гонка key-value-героев / Руслан Рагимов, Светлана Ла...
 
Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?Слои тестового фрамеворка. Что? Где? Когда?
Слои тестового фрамеворка. Что? Где? Когда?
 
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
Честное перформанс-тестирование / Дмитрий Пивоваров (ZeroTurnaround)
 
Развитие или смерть
Развитие или смертьРазвитие или смерть
Развитие или смерть
 
C++ Core Guidelines
C++ Core Guidelines C++ Core Guidelines
C++ Core Guidelines
 

Similar to The beast is becoming functional

Understanding Reflection
Understanding ReflectionUnderstanding Reflection
Understanding Reflection
Tamir Khason
 
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
MongoDB
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
David Giard
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
Peter Gfader
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
Abou Bakr Ashraf
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
Donal Fellows
 
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave ClubJoining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
Data Con LA
 
C programming 28 program
C programming 28 programC programming 28 program
C programming 28 program
F Courses
 
Polygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdfPolygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdf
apnafreez
 
Polygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdfPolygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdf
apnafreez
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
Derek Dhammaloka
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
Pascal-Louis Perez
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
Bartlomiej Filipek
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
ThomasHorta
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 

Similar to The beast is becoming functional (17)

Understanding Reflection
Understanding ReflectionUnderstanding Reflection
Understanding Reflection
 
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
MongoDB Days Silicon Valley: From Story to Document: Applying MongoDB Thinkin...
 
Intro to object oriented programming
Intro to object oriented programmingIntro to object oriented programming
Intro to object oriented programming
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
Visula C# Programming Lecture 2
Visula C# Programming Lecture 2Visula C# Programming Lecture 2
Visula C# Programming Lecture 2
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave ClubJoining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
Joining the Club: Using Spark to Accelerate Big Data at Dollar Shave Club
 
C programming 28 program
C programming 28 programC programming 28 program
C programming 28 program
 
Polygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdfPolygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdf
 
Polygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdfPolygon.javapublic class Polygon { private int numSides; priva.pdf
Polygon.javapublic class Polygon { private int numSides; priva.pdf
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Listing for TryLambdaExpressions
Listing for TryLambdaExpressionsListing for TryLambdaExpressions
Listing for TryLambdaExpressions
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Vocabulary Types in C++17
Vocabulary Types in C++17Vocabulary Types in C++17
Vocabulary Types in C++17
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 

More from corehard_by

C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
corehard_by
 
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
corehard_by
 
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений ОхотниковC++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
corehard_by
 
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр ТитовC++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
corehard_by
 
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
corehard_by
 
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья ШишковC++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
corehard_by
 
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
corehard_by
 
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
corehard_by
 
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
corehard_by
 
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
corehard_by
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
corehard_by
 
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
corehard_by
 
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел ФилоновC++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
corehard_by
 
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan ČukićC++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
corehard_by
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
corehard_by
 
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон ПолухинC++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
corehard_by
 
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
corehard_by
 
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
corehard_by
 
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
corehard_by
 
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
corehard_by
 

More from corehard_by (20)

C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...
 
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
C++ CoreHard Autumn 2018. Что должен знать каждый C++ программист или Как про...
 
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений ОхотниковC++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотников
 
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр ТитовC++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титов
 
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...
 
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья ШишковC++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишков
 
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...
 
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...
 
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...
 
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...
 
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...
 
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...
 
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел ФилоновC++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филонов
 
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan ČukićC++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukić
 
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia KazakovaC++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakova
 
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон ПолухинC++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухин
 
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...
 
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019
 
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019Как помочь и как помешать компилятору. Андрей Олейников ➠  CoreHard Autumn 2019
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019
 
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019Автоматизируй это. Кирилл Тихонов ➠  CoreHard Autumn 2019
Автоматизируй это. Кирилл Тихонов ➠ CoreHard Autumn 2019
 

Recently uploaded

FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
Data Hops
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
Dinusha Kumarasiri
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
Postman
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
Shinana2
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
Intelisync
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
Brandon Minnick, MBA
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
maazsz111
 

Recently uploaded (20)

FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3FREE A4 Cyber Security Awareness  Posters-Social Engineering part 3
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Azure API Management to expose backend services securely
Azure API Management to expose backend services securelyAzure API Management to expose backend services securely
Azure API Management to expose backend services securely
 
WeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation TechniquesWeTestAthens: Postman's AI & Automation Techniques
WeTestAthens: Postman's AI & Automation Techniques
 
dbms calicut university B. sc Cs 4th sem.pdf
dbms  calicut university B. sc Cs 4th sem.pdfdbms  calicut university B. sc Cs 4th sem.pdf
dbms calicut university B. sc Cs 4th sem.pdf
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024A Comprehensive Guide to DeFi Development Services in 2024
A Comprehensive Guide to DeFi Development Services in 2024
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
Choosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptxChoosing The Best AWS Service For Your Website + API.pptx
Choosing The Best AWS Service For Your Website + API.pptx
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
SAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloudSAP S/4 HANA sourcing and procurement to Public cloud
SAP S/4 HANA sourcing and procurement to Public cloud
 

The beast is becoming functional

  • 1. The beast is becoming functional CoreHard, Minsk 2017 Ivan Čukić ivan.cukic@kde.org http://cukic.co
  • 2. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Disclaimer Make your code readable. Pretend the next person who looks at your code is a psychopath and they know where you live. Philip Wadler 2
  • 3. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Connections 3
  • 4. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Functional programming Higher-order functions Algebraic data types Purity Laziness etc. 4
  • 6. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” #include <functional> #include <algorithm> 6
  • 7. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” 7
  • 8. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” 7
  • 9. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” template <typename It, typename Predicate> std::pair<It, It> move_selection(It first, It last, It destination, Pred predicate) { return std::make_pair( std::stable_partition(first, destination, negate(predicate)); std::stable_partition(destination, last, predicate) ); } 8
  • 10. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” operator() + templates 9
  • 11. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” std::multiplies<float>() std::bind1st(⋯) arg1 * arg2 boost.phoenix 10
  • 12. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine that Goes ”Ping” std::multiplies<>() std::bind(⋯) arg1 * arg2 boost.phoenix 11
  • 13. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Machine Stopped Problems: One-off functions Problems with iterators Problem with tuples 12
  • 15. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Lambdas Lambdas – syntactic sugar for creating function objects: std::stable_partition( first, destination, [&] (auto&& value) { return !predicate(FWD(value)); }); // FWD - std::forward<decltype(value)>(value) 14
  • 16. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Algorithm composition 15
  • 17. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Algorithm composition people.erase( std::remove_if(people.begin(), people.end(), is_not_female), people.end()); // or std::copy_if std::transform(people.begin(), people.end(), std::back_inserer(names), &person::name); 16
  • 18. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Algorithm composition Ranges to the rescue: people | filter(is_female) | transform(&person::name); 17
  • 19. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Algorithm composition auto mistery_function(vector<gadget> gadgets, int offset, int count) { vector<gadget> result; int skipped = 0, took = 0; for (const auto &gadget: gadgets) { if (is_container(gadget)) continue; vector<gadget> children; for (const auto &child: children(gadget)) { if (is_visible(child)) { if (skipped < offset) { skipped++; } else if (took <= count) { took++; children.push_back(child); } } } copy(children.cbegin(), children.cend(), back_inserter(result)); } return result; } 18
  • 20. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Algorithm composition auto mistery_function(vector<gadget> gadgets, int offset, int count) { return gadgets | filtered(is_container) | transformed(children) | flatten() | filtered(is_visible) | drop(offset) | take(count); } 19
  • 21. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Meaning of Tuples template <typename It, typename Predicate> std::pair<It, It> move_selection(It first, It last, It destination, Pred predicate) { ⋯ } 20
  • 22. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Meaning of Tuples auto selection = move_selection(⋯); std::sort(selection.first, selection.second); 21
  • 23. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard The Meaning of Tuples auto [ selected_begin, selected_end ] = move_selection(⋯); std::sort(selected_begin, selected_end); 22
  • 25. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting Problem: Create a program that fetches a web page and counts the words in that page 24
  • 26. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting States: The initial state The counting state The final state 25
  • 27. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting struct state_t { bool started = false; bool finished = false; unsigned count = 0; not needed until started string url; socket_t web_page; }; 26
  • 28. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting struct state_t { bool started = false; bool finished = false; unsigned count = 0; string url; not needed after started socket_t web_page; }; 26
  • 29. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting struct state_t { bool started = false; bool finished = false; unsigned count = 0; string url; socket_t web_page; needed only while working }; 26
  • 30. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Word counting struct state_t { bool started = false; bool finished = true; unsigned count = 42; string url = ”http://isocpp.org”; socket_t web_page = ⋯; }; 27
  • 31. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Fighting each other 28
  • 32. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types A sum of types A and B is a type that contains an instance of A or an instance of B, but not both at the same time. A ∪ B 29
  • 33. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance We can implement sum types through inheritance. Create a state_t super-class, and sub-classes for each of the states. 30
  • 34. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class state_t { protected: state_t(int type) we can not create instances : type(type) of this type directly { } public: const int type; virtual ~state_t() {}; }; 31
  • 35. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class init_t: public state_t { public: enum { id = 0 }; init_t() : state_t(id) { } string url; }; 32
  • 36. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class running_t: public state_t { public: enum { id = 1 }; init_t() : state_t(id) { } unsigned m_count = 0; socket_t m_web_page; }; 33
  • 37. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class finished_t: public state_t { public: enum { id = 2 }; init_t() : state_t(id) { } const unsigned m_count = 0; }; 34
  • 38. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance 35
  • 39. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class program_t { public: program_t() The initial : m_state(make_unique<init_t>()) program state { } void counting_finished() { assert(m_state->type == running_t::id); auto state = static_cast<running_t*>(m_state.get()); m_state.reset( make_unique<finished_t>(state->m_count)); } private: unique_ptr<state_t> m_state; }; 36
  • 40. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class program_t { public: program_t() : m_state(make_unique<init_t>()) { } void counting_finished() { assert(m_state->type == running_t::id); We must have been running auto state = in order for this function static_cast<running_t*>(m_state.get()); to be called m_state.reset( make_unique<finished_t>(state->m_count)); } private: unique_ptr<state_t> m_state; }; 36
  • 41. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance class program_t { public: program_t() : m_state(make_unique<init_t>()) { } void counting_finished() { assert(m_state->type == running_t::id); auto state = static_cast<running_t*>(m_state.get()); m_state.reset( make_unique<finished_t>(state->m_count)); Changing state } private: unique_ptr<state_t> m_state; }; 36
  • 42. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Sum types using inheritance We can have no invalid states Set of states is easily extendable (open sum types) Automatic resource disposal for resources tied to a particular state Bad: A lot of boilerplate 37
  • 43. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions 38
  • 44. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions struct init_t { string url; }; struct running_t { unsigned m_count; socket_t m_web_page; }; struct finished_t { const unsigned m_count; } std::variant < init_t We can just list all , running_t the types that we want , finished_t to use for state handling > m_state; 39
  • 45. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions void counting_finished() { auto *state = get_if<running_t>(&m_state); assert(state != nullptr); m_state = finished_t(state->m_count); } 40
  • 46. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions We can have no invalid states Set of states is fixed (closed sum types) Automatic resource disposal for resources tied to a particular state No boilerplate 41
  • 47. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions std::visit( [] (const auto& value) { std::cout << value << std::endl; }, m_state); 42
  • 48. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Type-safe unions template <typename... Ts> struct overloaded: Ts... { using Ts::operator()...; }; std::visit(overloaded { [&] (const init_t& state) { ⋯ }, [&] (const running_t& state) { ⋯ }, [&] (const finished_t& state) { ⋯ } }, m_state); 43
  • 49. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Optional values std::optional<T> – a sum type of T and nothing struct nothing_t {}; template <typename T> using optional = variant<nothing_t, T>; But with a nicer API. 44
  • 50. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Optional values When we have optional arguments When a function can fail ... 45
  • 51. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Optional values template <typename T, typename Variant> optional<T> get_if(const Variant& variant) { T* ptr = std::get_if<T>(&variant); if (ptr) { return *ptr; } else { return optional<T>(); } } 46
  • 52. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling The optional does not keep information about the error. template<typename T, typename E = std::exception_ptr> class expected { public: // ⋯ private: union { T m_value; E m_error; }; bool m_valid; }; 47
  • 53. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling template<typename T, typename E = std::exception_ptr> class expected { public: const T& get() const { if (!m_valid) { throw logic_error(”Missing a value”); } return m_value; } // ⋯ private: // ⋯ }; 48
  • 54. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling template<typename T, typename E = std::exception_ptr> class expected { public: template <typename... ConsParams> static expected success(ConsParams&& ...params) { expected result; result.m_valid = true; new (&result.m_value) T(forward<ConsParams>(params)...); return result; } // ⋯ private: // ⋯ }; 49
  • 55. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling template<typename T, typename E = std::exception_ptr> class expected { public: ~expected() { if (m_valid) { m_value.~T(); } else { m_error.~E(); } } // ⋯ private: // ⋯ }; 50
  • 56. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling template<typename T, typename E = std::exception_ptr> class expected { public: expected(const expected& other) : m_valid(other.m_valid) { if (m_valid) { new (&m_value) T(other.m_value); } else { new (&m_error) E(other.m_error); } } // ⋯ private: // ⋯ }; 51
  • 57. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling public: void swap(expected& other) { using std::swap; if (m_valid) { if (other.m_valid) { swap(m_value, other.m_value); } else { auto temp = std::move(other.m_error); other.m_error.~E(); new (&other.m_value) T(std::move(m_value)); m_value.~T(); new (&m_error) E(std::move(temp)); std::swap(m_valid, other.m_valid); } } else { // ⋯ 52
  • 58. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Error handling public: void swap(expected& other) { using std::swap; if (m_valid) { // ⋯ } else { if (other.m_valid) { other.swap(*this); } else { swap(m_error, other.m_error); } } } }; 53
  • 59. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling optional and expected values optional<string> login = current_user(); if (!user) return error optional<user_t> user = get_info(login.get()); if (!user) return error optional<string> full_name = get_full_name(user.get()); if (full_name) return error ⋯ 54
  • 60. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling optional and expected values Optional (and expected) values are like containers with at most one element. 55
  • 61. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling optional and expected values current_user: () -> optional<string> get_info: string -> optional<user_t> get_full_name: user_t -> optional<string> current_user() | transform(get_info) | transform(get_full_name) | ⋯ ; 56
  • 62. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling optional and expected values current_user: () -> optional<string> get_info: string -> optional<user_t> get_full_name: user_t -> optional<string> current_user() | mbind(get_info) | mbind(get_full_name) | ⋯ ; 57
  • 64. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling future values Future values are like containers that will get the value later. 59
  • 65. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling future values current_user: () -> future<string> get_info: string -> future<user_t> get_full_name: user_t -> future<string> current_user() | mbind(get_info) | mbind(get_full_name) | ⋯ ; 60
  • 66. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Handling future values current_user: () -> future<string> get_info: string -> future<user_t> get_full_name: user_t -> future<string> current_user() .then(get_info) .then(get_full_name) ⋯ ; 61
  • 67. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Imperative on top current_user: () -> future<string> get_info: string -> future<user_t> get_full_name: user_t -> future<string> auto user = co_await current_user(); auto info = co_await get_info(user); auto name = co_await get_full_name(info); 62
  • 68. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Imperative on top co_await expression is equivalent to: { auto && tmp = <expr>; if (!await_ready(tmp)) { await_suspend(tmp, continuation); } return await_resume(tmp); } 63
  • 69. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Imperative on top A core-language feature to implement .then 64
  • 70. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Imperative on top A core-language feature to implement mbind 64
  • 71. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Imperative on top current_user: () -> optional<string> get_info: string -> optional<user_t> get_full_name: user_t -> optional<string> auto user = co_await current_user(); auto info = co_await get_info(user); auto name = co_await get_full_name(info); 65
  • 72. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Summary First, higher-order functions Then, alternative type design safe state handling with sum types Combination of the two Monadic design Finally baking the monad into the core-language 66
  • 73. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Compilation process Write imperative co_await-based code Converted to functional (monadic) design Uses TMP for the type Unwraps all into imperative code Converted to a single-assignment internal compiler language To be finally converted to assembly 67
  • 74. The Miracle of Birth Growth and Learning Fighting Each Other The Autumn Years CODE: ctwcorehard Answers? Questions! Questions? Answers! Kudos (in chronological order): Friends at KDE Saša Malkov and Zoltan Porkolab Антон Наумович and Сергей Платонов MEAP – Manning Early Access Program Functional Programming in C++ cukic.co/to/fp-in-cpp Discount code (40% off all Manning books): ctwcorehard 68