SlideShare a Scribd company logo
1 of 89
Download to read offline
Functional C++
@KevlinHenney
https://twitter.com/mfeathers/status/29581296216
functional
programming
higher-order functions
recursion
statelessness
first-class functions
immutability
pure functions
unification
declarative
pattern matching
non-strict evaluation
idempotence
lists
mathematics
lambdas
currying
monads
class heating_system
{
public:
void turn_on();
void turn_off();
...
};
class timer
{
public:
timer(time_of_day when, command & what);
void run();
void cancel();
...
};
class command
{
public:
virtual void execute() = 0;
...
};
class turn_on : public command
{
public:
explicit turn_on(heating_system & heating)
: heating(heating)
{
}
void execute() override
{
heating.turn_on();
}
private:
heating_system & heating;
};
class turn_off : public command
{
public:
explicit turn_off(heating_system & heating)
: heating(heating)
class turn_on : public command
{
public:
explicit turn_on(heating_system & heating)
: heating(heating)
{
}
void execute() override
{
heating.turn_on();
}
private:
heating_system & heating;
};
class turn_off : public command
{
public:
explicit turn_off(heating_system & heating)
: heating(heating)
{
}
void execute() override
{
heating.turn_off();
}
private:
heating_system & heating;
};
class timer
{
public:
timer(
time_of_day when,
void execute(void * context), void * context);
void run();
void cancel();
...
};
void turn_on(void * context)
{
static_cast<heating_system *>(context)->turn_on();
}
void turn_off(void * context)
{
static_cast<heating_system *>(context)->turn_off();
}
class timer
{
public:
timer(time_of_day when, function<void()> what);
void run();
void cancel();
...
};
timer on(
time_on,
std::bind(&heating_system::turn_on, &heating));
timer off(
time_off,
std::bind(&heating_system::turn_off, &heating));
timer on(time_on, [&] { heating.turn_on(); });
timer off(time_off, [&] { heating.turn_off(); });
William Cook, "On Understanding Data Abstraction, Revisited"
[](){}
[](){}()
paraskevidekatriaphobia, noun
 The superstitious fear of Friday 13th.
 Contrary to popular myth, this superstition is relatively recent
(19th century) and did not originate during or before the
medieval times.
 Paraskevidekatriaphobia (or friggatriskaidekaphobia) also
reflects a particularly egocentric attributional bias: the universe
is prepared to rearrange causality and probability around the
believer based on an arbitrary and changeable calendar system,
in a way that is sensitive to geography, culture and time zone.
WordFriday.com
struct tm next_friday_13th(const struct tm * after)
{
struct tm next = *after;
enum { daily_secs = 24 * 60 * 60 };
time_t seconds =
mktime(&next) +
(next.tm_mday == 13 ? daily_secs : 0);
do
{
seconds += daily_secs;
next = *localtime(&seconds);
}
while(next.tm_mday != 13 || next.tm_wday != 5);
return next;
}
std::find_if(
++begin, day_iterator(),
[](const std::tm & day)
{
return day.tm_mday == 13 && day.tm_wday == 5;
});
class day_iterator : public std::iterator<...>
{
public:
day_iterator() ...
explicit day_iterator(const std::tm & start) ...
const std::tm & operator*() const
{
return day;
}
const std::tm * operator->() const
{
return &day;
}
day_iterator & operator++()
{
std::time_t seconds = std::mktime(&day) + 24 * 60 * 60;
day = *std::localtime(&seconds);
return *this;
}
day_iterator operator++(int) ...
...
};
http://www.adampetersen.se/articles/fizzbuzz.htm
http://www.adampetersen.se/articles/fizzbuzz.htm
enum fizzbuzzed
{
fizz = -2,
buzz = -1,
fizzbuzz = 0,
first = 1,
last = 100
};
constexpr fizzbuzzed fizzbuzz_of(int n)
{
return
n % 3 == 0 && n % 5 == 0 ? fizzbuzz :
n % 3 == 0 ? fizz :
n % 5 == 0 ? buzz :
fizzbuzzed(n);
}
When it is not
necessary to
change, it is
necessary not to
change.
Lucius Cary
const
&
&&
Immutable Value
References to value objects are commonly distributed and
stored in fields. However, state changes to a value caused
by one object can have unexpected and unwanted side-
effects for any other object sharing the same value
instance. Copying the value can reduce the
synchronization overhead, but can also incur object
creation overhead.
Therefore:
Define a value object type whose instances are immutable.
The internal state of a value object is set at construction
and no subsequent modifications are allowed.
Copied Value
Value objects are commonly distributed and stored in
fields. If value objects are shared between threads,
however, state changes caused by one object to a value
can have unexpected and unwanted side effects for any
other object sharing the same value instance. In a multi-
threaded environment shared state must be synchronized
between threads, but this introduces costly overhead for
frequent access.
Therefore:
Define a value object type whose instances are copyable.
When a value is used in communication with another
thread, ensure that the value is copied.
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
void set_year(int);
void set_month(int);
void set_day_in_month(int);
...
};
Just because you
have a getter,
doesn't mean you
should have a
matching setter.
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
void set(int year, int month, int day_in_month);
...
};
today.set(2015, 9, 14);
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
};
today = date(2015, 9, 14);
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
};
today = date { 2015, 9, 14 };
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
};
today = { 2015, 9, 14 };
"Get something"
is an imperative
with an expected
side effect.
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int get_year() const;
int get_month() const;
int get_day_in_month() const;
...
};
class date
{
public:
date(int year, int month, int day_in_month);
date(const date &);
date & operator=(const date &);
...
int year() const;
int month() const;
int day_in_month() const;
...
};
Conversions
Overloading
Derivation
Genericity
Mutability
Referential transparency is a very
desirable property: it implies that
functions consistently yield the same
results given the same input,
irrespective of where and when they are
invoked. That is, function evaluation
depends less—ideally, not at all—on the
side effects of mutable state.
Edward Garson
"Apply Functional Programming Principles"
Asking a question
should not change
the answer.
Bertrand Meyer
Asking a question
should not change
the answer, and
nor should asking
it twice!
A book is simply the
container of an idea like
a bottle; what is inside
the book is what matters.
Angela Carter
// "FTL" (Functional Template Library :->)
// container style
template<typename ValueType>
class container
{
public:
typedef const ValueType value_type;
typedef ... iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
...
container & operator=(const container &);
...
};
template<typename ValueType>
class set
{
public:
typedef const ValueType * iterator;
...
set(std::initializer_list<ValueType> values);
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
iterator find(const ValueType &) const;
std::size_t count(const ValueType &) const;
iterator lower_bound(const ValueType &) const;
iterator upper_bound(const ValueType &) const;
pair<iterator, iterator> equal_range(const ValueType &) const;
...
private:
ValueType * members;
std::size_t cardinality;
};
set<int> c { 2, 9, 9, 7, 9, 2, 4, 5, 8 };
template<typename ValueType>
class array
{
public:
typedef const ValueType * iterator;
...
array(std::initializer_list<ValueType> values);
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
...
private:
ValueType * elements;
std::size_t length;
};
array<int> c { 2, 9, 9, 7, 9, 2, 4, 5, 8 };
In computing, a persistent data structure is a data structure
that always preserves the previous version of itself when it is
modified. Such data structures are effectively immutable, as
their operations do not (visibly) update the structure in-place,
but instead always yield a new updated structure.
http://en.wikipedia.org/wiki/Persistent_data_structure
(A persistent data structure is not a data structure committed
to persistent storage, such as a disk; this is a different and
unrelated sense of the word "persistent.")
template<typename ValueType>
class vector
{
public:
typedef const ValueType * iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
vector pop_front() const;
vector pop_back() const;
...
private:
ValueType * anchor;
iterator from, until;
};
template<typename ValueType>
class vector
{
public:
typedef const ValueType * iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
vector pop_front() const;
vector pop_back() const;
...
private:
ValueType * anchor;
iterator from, until;
};
template<typename ValueType>
class vector
{
public:
typedef const ValueType * iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
vector popped_front() const;
vector popped_back() const;
...
private:
ValueType * anchor;
iterator from, until;
};
template<typename ValueType>
class vector
{
public:
typedef const ValueType * iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
vector popped_front() const;
vector popped_back() const;
...
private:
ValueType * anchor;
iterator from, until;
};
I still have a deep fondness for the
Lisp model. It is simple, elegant, and
something with which all developers
should have an infatuation at least
once in their programming life.
Kevlin Henney
"A Fair Share (Part I)", CUJ C++ Experts Forum, October 2002
lispt
template<typename ValueType>
class list
{
public:
class iterator;
...
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & front() const;
list popped_front() const;
list pushed_front() const;
...
private:
struct link
{
link(const ValueType & value, link * next);
ValueType value;
link * next;
};
link * head;
std::size_t length;
};
Hamlet: Yea, from the table
of my memory I'll wipe away
all trivial fond records.
William Shakespeare
The Tragedy of Hamlet
[Act I, Scene 5]
Garbage collection [...] is optional
in C++; that is, a garbage collector
is not a compulsory part of an
implementation.
Bjarne Stroustrup
http://stroustrup.com/C++11FAQ.html
assert(
std::get_pointer_safety() ==
std::pointer_safety::strict);
Ophelia: 'Tis in my memory
locked, and you yourself shall
keep the key of it.
William Shakespeare
The Tragedy of Hamlet
[Act I, Scene 3]
A use-counted class is more
complicated than a non-use-
counted equivalent, and all of
this horsing around with use
counts takes a significant
amount of processing time.
Robert Murray
C++ Strategies and Tactics
template<typename ValueType>
class vector
{
public:
typedef const ValueType * iterator;
...
bool empty() const;
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & operator[](std::size_t) const;
const ValueType & front() const;
const ValueType & back() const;
const ValueType * data() const;
vector popped_front() const;
vector popped_back() const;
...
private:
std::shared_ptr<ValueType> anchor;
iterator from, until;
};
Uses std::default_delete<ValueType[]>, but
cannot be initialised from std::make_shared
template<typename ValueType>
class list
{
public:
class iterator;
...
std::size_t size() const;
iterator begin() const;
iterator end() const;
const ValueType & front() const;
list popped_front() const;
list pushed_front() const;
...
private:
struct link
{
link(const ValueType & value, std::shared_ptr<link> next);
ValueType value;
std::shared_ptr<link> next;
};
std::shared_ptr<link> head;
std::size_t length;
};
{
list<Anything> chain;
std::fill_n(
std::front_inserter(chain),
how_many,
something);
}
On destruction, deletion of links is recursive
through each link, causing the stack to blow up
for surprisingly small values of how_many.
Concurrency
Concurrency
Threads
Concurrency
Threads
Locks
All computers
wait at the
same speed.
Some people, when confronted with a
problem, think, "I know, I'll use threads,"
and then two they hav erpoblesms.
Ned Batchelder
https://twitter.com/#!/nedbat/status/194873829825327104
Shared memory is like a canvas where
threads collaborate in painting images,
except that they stand on the opposite
sides of the canvas and use guns rather
than brushes. The only way they can
avoid killing each other is if they shout
"duck!" before opening fire.
Bartosz Milewski
"Functional Data Structures and Concurrency in C++"
http://bartoszmilewski.com/2013/12/10/functional-data-structures-and-concurrency-in-c/
Mutable
Immutable
Unshared Shared
Unshared mutable
data needs no
synchronisation
Unshared immutable
data needs no
synchronisation
Shared mutable
data needs
synchronisation
Shared immutable
data needs no
synchronisation
Mutable
Immutable
Unshared Shared
Unshared mutable
data needs no
synchronisation
Unshared immutable
data needs no
synchronisation
Shared mutable
data needs
synchronisation
Shared immutable
data needs no
synchronisation
The Synchronisation Quadrant
std::string fizzbuzz(int n)
{
return
n % 3 == 0 && n % 5 == 0 ? "FizzBuzz" :
n % 3 == 0 ? "Fizz" :
n % 5 == 0 ? "Buzz" :
std::to_string(n);
}
void fizzbuzzer(
channel<int> & receive,
channel<std::string> & send)
{
for(int n; receive >> n;)
send << fizzbuzz(n);
}
int main()
{
channel<int> out;
channel<std::string> back;
std::thread fizzbuzzing(fizzbuzzer, out, back)
for(int n = 1; n <= 100; ++n)
{
out << n;
std::string result;
back >> result;
std::cout << result << "n";
}
...
}
Sender Receiver A
Message 1Message 3
Receiver B
In response to a message that it receives, an actor
can make local decisions, create more actors, send
more messages, and determine how to respond to
the next message received.
http://en.wikipedia.org/wiki/Actor_model
Multithreading is just one
damn thing after, before, or
simultaneous with another.
Andrei Alexandrescu
Actor-based concurrency is
just one damn message after
another.
Go with
the flow.
Queens of the Stone Age

More Related Content

What's hot

Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...Vietnam Open Infrastructure User Group
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QMLICS
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式Shengyou Fan
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google MockICS
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...Edureka!
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observablesStefan Charsley
 
Dossier de rapport_de_tests_v1.00
Dossier de rapport_de_tests_v1.00Dossier de rapport_de_tests_v1.00
Dossier de rapport_de_tests_v1.00Arnold Stellio
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIICS
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IICS
 
Leveraging Nexus Repository Manager at the Heart of DevOps
Leveraging Nexus Repository Manager at the Heart of DevOpsLeveraging Nexus Repository Manager at the Heart of DevOps
Leveraging Nexus Repository Manager at the Heart of DevOpsSeniorStoryteller
 
老派浪漫:用 Kotlin 寫 Command Line 工具
老派浪漫:用 Kotlin 寫 Command Line 工具老派浪漫:用 Kotlin 寫 Command Line 工具
老派浪漫:用 Kotlin 寫 Command Line 工具Shengyou Fan
 
Social network with microservices
Social network with microservicesSocial network with microservices
Social network with microservicesViet Tran
 

What's hot (20)

Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
Bare Metal Cluster with Kubernetes, Istio and Metallb | Nguyen Phuong An, Ngu...
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
In-Depth Model/View with QML
In-Depth Model/View with QMLIn-Depth Model/View with QML
In-Depth Model/View with QML
 
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
[GDG Kaohsiung DevFest 2023] 以 Compose 及 Kotlin Multiplatform 打造多平台應用程式
 
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
[Webinar] Qt Test-Driven Development Using Google Test and Google Mock
 
Dropwizard
DropwizardDropwizard
Dropwizard
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...JavaScript Interview Questions and Answers | Full Stack Web Development Train...
JavaScript Interview Questions and Answers | Full Stack Web Development Train...
 
Jenkins CI
Jenkins CIJenkins CI
Jenkins CI
 
Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2Qt Application Programming with C++ - Part 2
Qt Application Programming with C++ - Part 2
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Jenkins
JenkinsJenkins
Jenkins
 
Dossier de rapport_de_tests_v1.00
Dossier de rapport_de_tests_v1.00Dossier de rapport_de_tests_v1.00
Dossier de rapport_de_tests_v1.00
 
Best Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part IIBest Practices in Qt Quick/QML - Part II
Best Practices in Qt Quick/QML - Part II
 
Best Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part IBest Practices in Qt Quick/QML - Part I
Best Practices in Qt Quick/QML - Part I
 
Ev3 student worksheets
Ev3 student worksheetsEv3 student worksheets
Ev3 student worksheets
 
Leveraging Nexus Repository Manager at the Heart of DevOps
Leveraging Nexus Repository Manager at the Heart of DevOpsLeveraging Nexus Repository Manager at the Heart of DevOps
Leveraging Nexus Repository Manager at the Heart of DevOps
 
老派浪漫:用 Kotlin 寫 Command Line 工具
老派浪漫:用 Kotlin 寫 Command Line 工具老派浪漫:用 Kotlin 寫 Command Line 工具
老派浪漫:用 Kotlin 寫 Command Line 工具
 
Social network with microservices
Social network with microservicesSocial network with microservices
Social network with microservices
 
Java 102
Java 102Java 102
Java 102
 

Viewers also liked

The Error of Our Ways
The Error of Our WaysThe Error of Our Ways
The Error of Our WaysKevlin Henney
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersKevlin Henney
 
Network security desighn principles and authentication
Network security desighn principles and authenticationNetwork security desighn principles and authentication
Network security desighn principles and authenticationEdgar Mwangangi
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Network Security
Network SecurityNetwork Security
Network SecurityMAJU
 
Network Security Presentation
Network Security PresentationNetwork Security Presentation
Network Security PresentationAllan Pratt MBA
 
Network Security Applications
Network Security ApplicationsNetwork Security Applications
Network Security ApplicationsHatem Mahmoud
 
Network Security and Cryptography
Network Security and CryptographyNetwork Security and Cryptography
Network Security and CryptographyAdam Reagan
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 
Worse Is Better, for Better or for Worse
Worse Is Better, for Better or for WorseWorse Is Better, for Better or for Worse
Worse Is Better, for Better or for WorseKevlin Henney
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Anton Bikineev
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeKevlin Henney
 
SOLID Deconstruction
SOLID DeconstructionSOLID Deconstruction
SOLID DeconstructionKevlin Henney
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 

Viewers also liked (20)

The Error of Our Ways
The Error of Our WaysThe Error of Our Ways
The Error of Our Ways
 
The Rule of Three
The Rule of ThreeThe Rule of Three
The Rule of Three
 
Seven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many ProgrammersSeven Ineffective Coding Habits of Many Programmers
Seven Ineffective Coding Habits of Many Programmers
 
Network security desighn principles and authentication
Network security desighn principles and authenticationNetwork security desighn principles and authentication
Network security desighn principles and authentication
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Network security
Network security Network security
Network security
 
Network Security
Network SecurityNetwork Security
Network Security
 
Network Security Presentation
Network Security PresentationNetwork Security Presentation
Network Security Presentation
 
Network security
Network securityNetwork security
Network security
 
Network Security Applications
Network Security ApplicationsNetwork Security Applications
Network Security Applications
 
Network Security and Cryptography
Network Security and CryptographyNetwork Security and Cryptography
Network Security and Cryptography
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 
Worse Is Better, for Better or for Worse
Worse Is Better, for Better or for WorseWorse Is Better, for Better or for Worse
Worse Is Better, for Better or for Worse
 
Writing good std::future&lt;c++>
Writing good std::future&lt;c++>Writing good std::future&lt;c++>
Writing good std::future&lt;c++>
 
The Worst Code
The Worst CodeThe Worst Code
The Worst Code
 
Declarative Thinking, Declarative Practice
Declarative Thinking, Declarative PracticeDeclarative Thinking, Declarative Practice
Declarative Thinking, Declarative Practice
 
SOLID Deconstruction
SOLID DeconstructionSOLID Deconstruction
SOLID Deconstruction
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
FizzBuzz Trek
FizzBuzz TrekFizzBuzz Trek
FizzBuzz Trek
 

Similar to Functional C++

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядомAndrey Akinshin
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
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
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancjiJakub Marchwicki
 
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfC++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfandreaplotner1
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of cTushar B Kute
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfsnewfashion
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfJAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfkarymadelaneyrenne19
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたAkira Maruoka
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmersMark Whitaker
 

Similar to Functional C++ (20)

Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
.NET 2015: Будущее рядом
.NET 2015: Будущее рядом.NET 2015: Будущее рядом
.NET 2015: Будущее рядом
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
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#
 
[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji[PL] O klasycznej, programistycznej elegancji
[PL] O klasycznej, programistycznej elegancji
 
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdfC++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
C++ code only(Retrieve of Malik D., 2015, p. 742) Programming Exer.pdf
 
An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Introduction to c part 2
Introduction to c   part  2Introduction to c   part  2
Introduction to c part 2
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdfSolve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
Solve the coding errors for upvotemake test-statsg++ -g -std=c++.pdf
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdfJAVA.Q4 Create a Time class. This class will represent a point in.pdf
JAVA.Q4 Create a Time class. This class will represent a point in.pdf
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
Chainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみたChainer-Compiler 動かしてみた
Chainer-Compiler 動かしてみた
 
C# for C++ programmers
C# for C++ programmersC# for C++ programmers
C# for C++ programmers
 

More from Kevlin Henney

The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical ExcellenceKevlin Henney
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical DevelopmentKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that LetterKevlin Henney
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid DeconstructionKevlin Henney
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayKevlin Henney
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test CasesKevlin Henney
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to ImmutabilityKevlin Henney
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-InKevlin Henney
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good NameKevlin Henney
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Kevlin Henney
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantKevlin Henney
 

More from Kevlin Henney (20)

Program with GUTs
Program with GUTsProgram with GUTs
Program with GUTs
 
The Case for Technical Excellence
The Case for Technical ExcellenceThe Case for Technical Excellence
The Case for Technical Excellence
 
Empirical Development
Empirical DevelopmentEmpirical Development
Empirical Development
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Lambda? You Keep Using that Letter
Lambda? You Keep Using that LetterLambda? You Keep Using that Letter
Lambda? You Keep Using that Letter
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Get Kata
Get KataGet Kata
Get Kata
 
Procedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went AwayProcedural Programming: It’s Back? It Never Went Away
Procedural Programming: It’s Back? It Never Went Away
 
Structure and Interpretation of Test Cases
Structure and Interpretation of Test CasesStructure and Interpretation of Test Cases
Structure and Interpretation of Test Cases
 
Agility ≠ Speed
Agility ≠ SpeedAgility ≠ Speed
Agility ≠ Speed
 
Refactoring to Immutability
Refactoring to ImmutabilityRefactoring to Immutability
Refactoring to Immutability
 
Old Is the New New
Old Is the New NewOld Is the New New
Old Is the New New
 
Turning Development Outside-In
Turning Development Outside-InTurning Development Outside-In
Turning Development Outside-In
 
Giving Code a Good Name
Giving Code a Good NameGiving Code a Good Name
Giving Code a Good Name
 
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
Clean Coders Hate What Happens To Your Code When You Use These Enterprise Pro...
 
Thinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation QuadrantThinking Outside the Synchronisation Quadrant
Thinking Outside the Synchronisation Quadrant
 
Code as Risk
Code as RiskCode as Risk
Code as Risk
 
Software Is Details
Software Is DetailsSoftware Is Details
Software Is Details
 
Game of Sprints
Game of SprintsGame of Sprints
Game of Sprints
 
Good Code
Good CodeGood Code
Good Code
 

Recently uploaded

How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROmotivationalword821
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 

Recently uploaded (20)

How To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTROHow To Manage Restaurant Staff -BTRESTRO
How To Manage Restaurant Staff -BTRESTRO
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 

Functional C++

  • 2.
  • 3.
  • 5.
  • 6. functional programming higher-order functions recursion statelessness first-class functions immutability pure functions unification declarative pattern matching non-strict evaluation idempotence lists mathematics lambdas currying monads
  • 8. class timer { public: timer(time_of_day when, command & what); void run(); void cancel(); ... }; class command { public: virtual void execute() = 0; ... };
  • 9. class turn_on : public command { public: explicit turn_on(heating_system & heating) : heating(heating) { } void execute() override { heating.turn_on(); } private: heating_system & heating; }; class turn_off : public command { public: explicit turn_off(heating_system & heating) : heating(heating)
  • 10. class turn_on : public command { public: explicit turn_on(heating_system & heating) : heating(heating) { } void execute() override { heating.turn_on(); } private: heating_system & heating; }; class turn_off : public command { public: explicit turn_off(heating_system & heating) : heating(heating) { } void execute() override { heating.turn_off(); } private: heating_system & heating; };
  • 11. class timer { public: timer( time_of_day when, void execute(void * context), void * context); void run(); void cancel(); ... };
  • 12. void turn_on(void * context) { static_cast<heating_system *>(context)->turn_on(); } void turn_off(void * context) { static_cast<heating_system *>(context)->turn_off(); }
  • 13. class timer { public: timer(time_of_day when, function<void()> what); void run(); void cancel(); ... };
  • 14. timer on( time_on, std::bind(&heating_system::turn_on, &heating)); timer off( time_off, std::bind(&heating_system::turn_off, &heating));
  • 15. timer on(time_on, [&] { heating.turn_on(); }); timer off(time_off, [&] { heating.turn_off(); });
  • 16. William Cook, "On Understanding Data Abstraction, Revisited"
  • 19.
  • 20.
  • 21. paraskevidekatriaphobia, noun  The superstitious fear of Friday 13th.  Contrary to popular myth, this superstition is relatively recent (19th century) and did not originate during or before the medieval times.  Paraskevidekatriaphobia (or friggatriskaidekaphobia) also reflects a particularly egocentric attributional bias: the universe is prepared to rearrange causality and probability around the believer based on an arbitrary and changeable calendar system, in a way that is sensitive to geography, culture and time zone. WordFriday.com
  • 22. struct tm next_friday_13th(const struct tm * after) { struct tm next = *after; enum { daily_secs = 24 * 60 * 60 }; time_t seconds = mktime(&next) + (next.tm_mday == 13 ? daily_secs : 0); do { seconds += daily_secs; next = *localtime(&seconds); } while(next.tm_mday != 13 || next.tm_wday != 5); return next; }
  • 23. std::find_if( ++begin, day_iterator(), [](const std::tm & day) { return day.tm_mday == 13 && day.tm_wday == 5; });
  • 24. class day_iterator : public std::iterator<...> { public: day_iterator() ... explicit day_iterator(const std::tm & start) ... const std::tm & operator*() const { return day; } const std::tm * operator->() const { return &day; } day_iterator & operator++() { std::time_t seconds = std::mktime(&day) + 24 * 60 * 60; day = *std::localtime(&seconds); return *this; } day_iterator operator++(int) ... ... };
  • 25.
  • 26.
  • 29. enum fizzbuzzed { fizz = -2, buzz = -1, fizzbuzz = 0, first = 1, last = 100 }; constexpr fizzbuzzed fizzbuzz_of(int n) { return n % 3 == 0 && n % 5 == 0 ? fizzbuzz : n % 3 == 0 ? fizz : n % 5 == 0 ? buzz : fizzbuzzed(n); }
  • 30. When it is not necessary to change, it is necessary not to change. Lucius Cary
  • 31. const
  • 32. &
  • 33. &&
  • 34.
  • 35. Immutable Value References to value objects are commonly distributed and stored in fields. However, state changes to a value caused by one object can have unexpected and unwanted side- effects for any other object sharing the same value instance. Copying the value can reduce the synchronization overhead, but can also incur object creation overhead. Therefore: Define a value object type whose instances are immutable. The internal state of a value object is set at construction and no subsequent modifications are allowed.
  • 36. Copied Value Value objects are commonly distributed and stored in fields. If value objects are shared between threads, however, state changes caused by one object to a value can have unexpected and unwanted side effects for any other object sharing the same value instance. In a multi- threaded environment shared state must be synchronized between threads, but this introduces costly overhead for frequent access. Therefore: Define a value object type whose instances are copyable. When a value is used in communication with another thread, ensure that the value is copied.
  • 37. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... void set_year(int); void set_month(int); void set_day_in_month(int); ... };
  • 38. Just because you have a getter, doesn't mean you should have a matching setter.
  • 39. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... void set(int year, int month, int day_in_month); ... }; today.set(2015, 9, 14);
  • 40. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... }; today = date(2015, 9, 14);
  • 41. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... }; today = date { 2015, 9, 14 };
  • 42. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... }; today = { 2015, 9, 14 };
  • 43. "Get something" is an imperative with an expected side effect.
  • 44. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int get_year() const; int get_month() const; int get_day_in_month() const; ... };
  • 45. class date { public: date(int year, int month, int day_in_month); date(const date &); date & operator=(const date &); ... int year() const; int month() const; int day_in_month() const; ... };
  • 47.
  • 48. Referential transparency is a very desirable property: it implies that functions consistently yield the same results given the same input, irrespective of where and when they are invoked. That is, function evaluation depends less—ideally, not at all—on the side effects of mutable state. Edward Garson "Apply Functional Programming Principles"
  • 49. Asking a question should not change the answer. Bertrand Meyer
  • 50. Asking a question should not change the answer, and nor should asking it twice!
  • 51. A book is simply the container of an idea like a bottle; what is inside the book is what matters. Angela Carter
  • 52. // "FTL" (Functional Template Library :->) // container style template<typename ValueType> class container { public: typedef const ValueType value_type; typedef ... iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; ... container & operator=(const container &); ... };
  • 53. template<typename ValueType> class set { public: typedef const ValueType * iterator; ... set(std::initializer_list<ValueType> values); ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; iterator find(const ValueType &) const; std::size_t count(const ValueType &) const; iterator lower_bound(const ValueType &) const; iterator upper_bound(const ValueType &) const; pair<iterator, iterator> equal_range(const ValueType &) const; ... private: ValueType * members; std::size_t cardinality; }; set<int> c { 2, 9, 9, 7, 9, 2, 4, 5, 8 };
  • 54. template<typename ValueType> class array { public: typedef const ValueType * iterator; ... array(std::initializer_list<ValueType> values); ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; ... private: ValueType * elements; std::size_t length; }; array<int> c { 2, 9, 9, 7, 9, 2, 4, 5, 8 };
  • 55. In computing, a persistent data structure is a data structure that always preserves the previous version of itself when it is modified. Such data structures are effectively immutable, as their operations do not (visibly) update the structure in-place, but instead always yield a new updated structure. http://en.wikipedia.org/wiki/Persistent_data_structure (A persistent data structure is not a data structure committed to persistent storage, such as a disk; this is a different and unrelated sense of the word "persistent.")
  • 56. template<typename ValueType> class vector { public: typedef const ValueType * iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; vector pop_front() const; vector pop_back() const; ... private: ValueType * anchor; iterator from, until; };
  • 57. template<typename ValueType> class vector { public: typedef const ValueType * iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; vector pop_front() const; vector pop_back() const; ... private: ValueType * anchor; iterator from, until; };
  • 58. template<typename ValueType> class vector { public: typedef const ValueType * iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; vector popped_front() const; vector popped_back() const; ... private: ValueType * anchor; iterator from, until; };
  • 59. template<typename ValueType> class vector { public: typedef const ValueType * iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; vector popped_front() const; vector popped_back() const; ... private: ValueType * anchor; iterator from, until; };
  • 60.
  • 61. I still have a deep fondness for the Lisp model. It is simple, elegant, and something with which all developers should have an infatuation at least once in their programming life. Kevlin Henney "A Fair Share (Part I)", CUJ C++ Experts Forum, October 2002
  • 62. lispt
  • 63. template<typename ValueType> class list { public: class iterator; ... std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & front() const; list popped_front() const; list pushed_front() const; ... private: struct link { link(const ValueType & value, link * next); ValueType value; link * next; }; link * head; std::size_t length; };
  • 64. Hamlet: Yea, from the table of my memory I'll wipe away all trivial fond records. William Shakespeare The Tragedy of Hamlet [Act I, Scene 5]
  • 65. Garbage collection [...] is optional in C++; that is, a garbage collector is not a compulsory part of an implementation. Bjarne Stroustrup http://stroustrup.com/C++11FAQ.html
  • 67. Ophelia: 'Tis in my memory locked, and you yourself shall keep the key of it. William Shakespeare The Tragedy of Hamlet [Act I, Scene 3]
  • 68. A use-counted class is more complicated than a non-use- counted equivalent, and all of this horsing around with use counts takes a significant amount of processing time. Robert Murray C++ Strategies and Tactics
  • 69. template<typename ValueType> class vector { public: typedef const ValueType * iterator; ... bool empty() const; std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & operator[](std::size_t) const; const ValueType & front() const; const ValueType & back() const; const ValueType * data() const; vector popped_front() const; vector popped_back() const; ... private: std::shared_ptr<ValueType> anchor; iterator from, until; }; Uses std::default_delete<ValueType[]>, but cannot be initialised from std::make_shared
  • 70. template<typename ValueType> class list { public: class iterator; ... std::size_t size() const; iterator begin() const; iterator end() const; const ValueType & front() const; list popped_front() const; list pushed_front() const; ... private: struct link { link(const ValueType & value, std::shared_ptr<link> next); ValueType value; std::shared_ptr<link> next; }; std::shared_ptr<link> head; std::size_t length; };
  • 71. { list<Anything> chain; std::fill_n( std::front_inserter(chain), how_many, something); } On destruction, deletion of links is recursive through each link, causing the stack to blow up for surprisingly small values of how_many.
  • 72.
  • 76. All computers wait at the same speed.
  • 77. Some people, when confronted with a problem, think, "I know, I'll use threads," and then two they hav erpoblesms. Ned Batchelder https://twitter.com/#!/nedbat/status/194873829825327104
  • 78. Shared memory is like a canvas where threads collaborate in painting images, except that they stand on the opposite sides of the canvas and use guns rather than brushes. The only way they can avoid killing each other is if they shout "duck!" before opening fire. Bartosz Milewski "Functional Data Structures and Concurrency in C++" http://bartoszmilewski.com/2013/12/10/functional-data-structures-and-concurrency-in-c/
  • 79. Mutable Immutable Unshared Shared Unshared mutable data needs no synchronisation Unshared immutable data needs no synchronisation Shared mutable data needs synchronisation Shared immutable data needs no synchronisation
  • 80. Mutable Immutable Unshared Shared Unshared mutable data needs no synchronisation Unshared immutable data needs no synchronisation Shared mutable data needs synchronisation Shared immutable data needs no synchronisation The Synchronisation Quadrant
  • 81.
  • 82. std::string fizzbuzz(int n) { return n % 3 == 0 && n % 5 == 0 ? "FizzBuzz" : n % 3 == 0 ? "Fizz" : n % 5 == 0 ? "Buzz" : std::to_string(n); }
  • 83. void fizzbuzzer( channel<int> & receive, channel<std::string> & send) { for(int n; receive >> n;) send << fizzbuzz(n); }
  • 84. int main() { channel<int> out; channel<std::string> back; std::thread fizzbuzzing(fizzbuzzer, out, back) for(int n = 1; n <= 100; ++n) { out << n; std::string result; back >> result; std::cout << result << "n"; } ... }
  • 85.
  • 86. Sender Receiver A Message 1Message 3 Receiver B In response to a message that it receives, an actor can make local decisions, create more actors, send more messages, and determine how to respond to the next message received. http://en.wikipedia.org/wiki/Actor_model
  • 87. Multithreading is just one damn thing after, before, or simultaneous with another. Andrei Alexandrescu
  • 88. Actor-based concurrency is just one damn message after another.
  • 89. Go with the flow. Queens of the Stone Age