SlideShare a Scribd company logo
Thinking In Functions
Alex Bolboacă,  @alexboly,  alex.bolboaca@mozaicworks.com
February 2019
Why this talk
The Journey
A few years back
Last year…
CppEurope
Video available: https://www.youtube.com/watch?v=7L6oryyzZXc
Then…
Book deal
About This Talk
• A practical approach to use functional programming in C++
• Focused on essentials and the mindset
• Not purist
• No maths
• Not touching on performance
• My Goal: You should find at least one technique you can use in your
code
Core Ideas
Two Fundamental Ideas
• Immutability
• Functions are data
Why Immutability?
Why Immutability?
The more obstacles one places in the translation between code and
behavior, the more mistakes (aka bugs) we can make and the least effective
we are as programmers.
Example of Mutable Code
How many implementation options exist?
int add(int& first, int& second){
...
}
Option 1
int add(int& first, int& second){
return first + second;
}
Option 2
int add(int& first, int& second){
return first += second;
}
Option 3
int add(int& first, int& second){
return second += first;
}
What’s the Semantics?
int add(int first, int second)
int add(int first, int& second)
int add(int& first, int second)
int add(int& first, int& second)
int add(int first, int* second)
int add(int& first, int* second)
int add(int* first, int* second)
int add(int* first, int second)
int add(int* first, int& second)
Immutable Code
// If standalone function
int add(const int& first, const int& second)
// If part of a class
int add(const int& first, const int& second) const
How many implementation options?
Immutable Code
// If standalone function
int add(const int& first, const int& second){
return first + second;
}
// If part of a class
int add(const int& first, const int& second) const{
return first + second;
}
Why Immutability?
Immutability simplifies our translation effort, allowing your brain to focus on
adding more behavior.
Functions Are Data
Not a New Idea In C++
• Function pointers
• Functors
Let’s Represent Functions As Data
// Lambda variable
auto add = [](int first, int second){
return first + second;
};
More details: http://en.cppreference.com/w/cpp/language/lambda
Careful: Lambdas can be mutable
// Mutable
auto increment = [](int& value){return ++value};
int aValue = 42;
int incremented = increment(42);
assert(incremented == 43);
assert(aValue == 43)
Careful: Immutable Lambda
• Function call operator is const
• Parameters use their own specifier
// Immutable
auto incrementImmutable = [](const int& value){
return value + 1;
};
int aValue = 42;
int incremented = increment(42);
assert(incremented == 43);
assert(aValue == 42)
Type Inference
// Does not compile
auto add(auto first, auto second){
return first + second;
}
// Works for any two values that have operator+ defined
auto add = [](const auto& first, const auto& second){
return first + second;
};
Value Capture
Lambdas can capture values from the context.
TEST_CASE(”type inference with lambdas”){
int first = 5;
auto add = [=](const auto& second){
return first + second;
};
CHECK_EQ(42, add(37));
CHECK_EQ(42.5, add(37.5));
}
Code Time
Code Time
Consequences
Functions are data.
We can do operations on data.
We can do operations on functions!
Operations on Functions
What is an Operation on Functions?
Any operation that takes one (or more functions) and returns a new function.
• Partial Application
• Functional Composition
• Currying
• Higher level functions
Partial Application
A function with n-1 parameters is obtained from a function with n
parameters by binding one parameter to a value.
using namespace std::placeholders;
auto divide = [](const auto& first, const auto& second){
return first/second;
};
int specialValue = 10;
auto divideSpecialValue = bind(divide, specialValue, _1);
// Equivalent with
// auto divideSpecialValue = [](const auto& second) {
// return 10 / second
// };
Functional Composition
Create a function h(x) from two functions f(y) and g(z), such that for any
value of x, h(x) = f(g(x)).
C++ doesn’t yet have a functional composition operator, so we have to write
our own function:
template<typename F, typename G>
auto compose(F f, G g){
return [f, g](auto x){
return f(g(x));
};
}
Example
auto increment = [](const auto& value){
return value + 1;
};
auto incrementTwice = compose(increment, increment);
/* Equivalent with:
auto incrementTwice = [&](const auto& value){
return increment(increment(value));
};
*/
CHECK_EQ(3, incrementTwice(1));
Currying
Decompose a function with N arguments into N functions with one argument
auto curriedAdd = [](const auto& first){
return [first](const auto& second){
return first + second;
};
};
Currying in C++
Unfortunately, there’s no operator that supports currying.
In pure functional languages, curry is done by default, and linked with
partial application. For example:
auto divide = [](const auto& first, const auto& second){
return first/second;
};
divide(5) => a new function that takes second as parameter, equ
Interesting Fact
Curry. Haskell Curry
Pass Functions as Parameters
TEST_CASE(”pass functions as parameters”){
vector<int> values{42, 1, 55, 23};
vector<int> expected{1, 23, 42, 55};
auto compare = [](const auto& first, const auto& second){
return (first < second);
};
sort(values.begin(), values.end(), compare);
CHECK_EQ(expected, values);
}
Short list of higher level functions
Find them in or
• find_if
• transform
• reduce / accumulate
• count_if
• all_of / any_of / none_of
• …
See examples on https://github.com/MozaicWorks/functionalCpp
Code Time
Code Time
Conclusions
We can create functions from other functions through partial application,
composition, currying.
We can understand better the functions we write due to immutability.
Applying Functional Programming
Problem: TicTacToe Result
Given a TicTacToe board that’s either empty or already has moves, print out
the result of the game if the game ended or that the game is still in progress.
Approach
1. Clearly define the input; give examples
2. Clearly define the output; give examples
3. Identify a chain of functional transformations you can apply on the
input data to turn it into the output data
Clearly Define the Output
• Game not started
• Game in progress
• X won
• O won
• Draw
Clearly Define the Input
Empty Board:
_ _ _
_ _ _
_ _ _
X won by line:
X X X
O O _
_ _ _
etc.
Turns out that …
X wins if
• any line is filled with X OR
• any column is filled with X OR
• the main diagonal is filled with X OR
• the secondary diagonal is filled with X
Transformations
board ->
collection(all lines, all columns, all diagonals) ->
if any(collection, filledWithX) ->
X won
where
filledWithX(line|column|diagonal L) =
all(token on L equals 'X')
Remove duplication with functional operators
• Functions with the same parameter? Partial application! Or classes!
• Functions with the same structure? Higher level functions!
• Chained calls? Function composition!
Code Time
Code Time
What I’m Exploring Next
Refactoring code through Immutability
Premise:
• Any program can be written as Input -> Pure Functions -> State change
(either UI or storage)
• This property of the code applies on multiple levels, even on a single
function
Refactoring Method
• Take a complex piece of code:
• extract a small piece of it as another method
• extract everything mutable as parameter
• until the method is immutable
• check by making everything const and compiling
• then decompose the long immutable function into smaller immutable
functions
• then recombine the functions into classes, based on the parameters
they use
We End Up With Functional OOP
• Data structures with set / get or public data
• “Processor” objects that receive data and return other data
• “Run and forget” objects: initialize, execute operations, throw it away
• Separate, pluggable, input / output objects
Hypothesis
Unconfirmed Hypothesis: this type of refactoring is safe even without tests.
(Or, we can easily generate tests for the immutable function with
property-based testing)
Conclusion
Immutability and functions as data can simplify programming
I invite you to try them out. Pick one and try it.
Learn more
Functional programming in C++: https:
//www.slideshare.net/alexboly/functional-programming-in-c-88970494
Hidden loops: https://www.slideshare.net/alexboly/hidden-loops
Removing structural duplication:
https://www.slideshare.net/alexboly/removing-structuralduplication
Learn more at Mozaic Works workshops
https://mozaicworks.com/training/c-plus-plus/
Pre-order my book!
Hands-on Functional Programming In C++ - http://bit.ly/FProgCpp
Q&A
Q&A

More Related Content

PPT
08 c++ Operator Overloading.ppt
PPTX
PPTX
INLINE FUNCTION IN C++
PPTX
Inline Functions and Default arguments
PPTX
Functions in C++ (OOP)
PPTX
Inline function in C++
PPTX
Inline function in C++
PPTX
Presentation on overloading
08 c++ Operator Overloading.ppt
INLINE FUNCTION IN C++
Inline Functions and Default arguments
Functions in C++ (OOP)
Inline function in C++
Inline function in C++
Presentation on overloading

What's hot (17)

PPTX
Function class in c++
PPTX
Function overloading
PPTX
Functions in c++
PPTX
Inline function
PDF
Beyond Mere Actors
PPTX
operator overloading & type conversion in cpp over view || c++
PPT
3d7b7 session4 c++
PPT
Lecture5
PPTX
Inline functions
PPT
C++ overloading
PPTX
operator overloading
PPTX
Operator overloading
PDF
Operator overloading
PPT
Functions in c++
PPTX
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
DOCX
Inline function(oops)
PPTX
Function overloading in c++
Function class in c++
Function overloading
Functions in c++
Inline function
Beyond Mere Actors
operator overloading & type conversion in cpp over view || c++
3d7b7 session4 c++
Lecture5
Inline functions
C++ overloading
operator overloading
Operator overloading
Operator overloading
Functions in c++
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Inline function(oops)
Function overloading in c++
Ad

Similar to Thinking in Functions (20)

PPT
PPT
Material 3 (4).ppt this ppt is about the
PDF
PPT
Polymorphism and function overloading_new.ppt
PDF
Functional programming in C++
PPTX
Function in C++, Methods in C++ coding programming
PPTX
Chp8_C++_Functions_Part2_User-defined functions.pptx
PPTX
6. Functions in C ++ programming object oriented programming
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
PPT
C++ Functions.ppt
PPT
02 functions, variables, basic input and output of c++
PPTX
Functional Programming in Swift
PPTX
History of asynchronous in .NET
PPTX
Silde of the cse fundamentals a deep analysis
PPT
C++ functions
PPT
C++ functions
PPT
14 operator overloading
PPT
C++ Function
PPTX
unit_2 (1).pptx
PPTX
Function Overloading Call by value and call by reference
Material 3 (4).ppt this ppt is about the
Polymorphism and function overloading_new.ppt
Functional programming in C++
Function in C++, Methods in C++ coding programming
Chp8_C++_Functions_Part2_User-defined functions.pptx
6. Functions in C ++ programming object oriented programming
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
C++ Functions.ppt
02 functions, variables, basic input and output of c++
Functional Programming in Swift
History of asynchronous in .NET
Silde of the cse fundamentals a deep analysis
C++ functions
C++ functions
14 operator overloading
C++ Function
unit_2 (1).pptx
Function Overloading Call by value and call by reference
Ad

More from Alexandru Bolboaca (20)

PDF
Refactor legacy code through pure functions
PDF
Design Without Types
PDF
Raising the Bar
PDF
The Journey to Master Code Design
PDF
What is good software design? And why it matters?
PDF
Agile Technical Leadership
PDF
TDD As If You Meant It
PDF
Usable Software Design
PDF
Hidden loops
PDF
Removing structural duplication
PDF
Continuous delivery
PDF
Why You Should Start Using Docker
PDF
Pyramid of-developer-skills
PDF
Applied craftsmanship
PDF
Pyramid of-developer-skills
PDF
Stay focused
PDF
Kanban intro
ODP
Unit testing-patterns
ODP
Incremental design, simply explained
ODP
Exploring design-alternatives-using-tdd
Refactor legacy code through pure functions
Design Without Types
Raising the Bar
The Journey to Master Code Design
What is good software design? And why it matters?
Agile Technical Leadership
TDD As If You Meant It
Usable Software Design
Hidden loops
Removing structural duplication
Continuous delivery
Why You Should Start Using Docker
Pyramid of-developer-skills
Applied craftsmanship
Pyramid of-developer-skills
Stay focused
Kanban intro
Unit testing-patterns
Incremental design, simply explained
Exploring design-alternatives-using-tdd

Recently uploaded (20)

PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Cost to Outsource Software Development in 2025
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
Download FL Studio Crack Latest version 2025 ?
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
Complete Guide to Website Development in Malaysia for SMEs
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Choose the Right IT Partner for Your Business in Malaysia
Computer Software and OS of computer science of grade 11.pptx
Wondershare Filmora 15 Crack With Activation Key [2025
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Oracle Fusion HCM Cloud Demo for Beginners
Operating system designcfffgfgggggggvggggggggg
Cost to Outsource Software Development in 2025
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Download FL Studio Crack Latest version 2025 ?
Monitoring Stack: Grafana, Loki & Promtail
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Why Generative AI is the Future of Content, Code & Creativity?
Navsoft: AI-Powered Business Solutions & Custom Software Development
iTop VPN Free 5.6.0.5262 Crack latest version 2025
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
iTop VPN 6.5.0 Crack + License Key 2025 (Premium Version)
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Complete Guide to Website Development in Malaysia for SMEs
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises

Thinking in Functions

  • 1. Thinking In Functions Alex Bolboacă,  @alexboly,  [email protected] February 2019
  • 4. A few years back
  • 5. Last year… CppEurope Video available: https://www.youtube.com/watch?v=7L6oryyzZXc
  • 7. About This Talk • A practical approach to use functional programming in C++ • Focused on essentials and the mindset • Not purist • No maths • Not touching on performance • My Goal: You should find at least one technique you can use in your code
  • 9. Two Fundamental Ideas • Immutability • Functions are data
  • 11. Why Immutability? The more obstacles one places in the translation between code and behavior, the more mistakes (aka bugs) we can make and the least effective we are as programmers.
  • 12. Example of Mutable Code How many implementation options exist? int add(int& first, int& second){ ... }
  • 13. Option 1 int add(int& first, int& second){ return first + second; }
  • 14. Option 2 int add(int& first, int& second){ return first += second; }
  • 15. Option 3 int add(int& first, int& second){ return second += first; }
  • 16. What’s the Semantics? int add(int first, int second) int add(int first, int& second) int add(int& first, int second) int add(int& first, int& second) int add(int first, int* second) int add(int& first, int* second) int add(int* first, int* second) int add(int* first, int second) int add(int* first, int& second)
  • 17. Immutable Code // If standalone function int add(const int& first, const int& second) // If part of a class int add(const int& first, const int& second) const How many implementation options?
  • 18. Immutable Code // If standalone function int add(const int& first, const int& second){ return first + second; } // If part of a class int add(const int& first, const int& second) const{ return first + second; }
  • 19. Why Immutability? Immutability simplifies our translation effort, allowing your brain to focus on adding more behavior.
  • 21. Not a New Idea In C++ • Function pointers • Functors
  • 22. Let’s Represent Functions As Data // Lambda variable auto add = [](int first, int second){ return first + second; }; More details: http://en.cppreference.com/w/cpp/language/lambda
  • 23. Careful: Lambdas can be mutable // Mutable auto increment = [](int& value){return ++value}; int aValue = 42; int incremented = increment(42); assert(incremented == 43); assert(aValue == 43)
  • 24. Careful: Immutable Lambda • Function call operator is const • Parameters use their own specifier // Immutable auto incrementImmutable = [](const int& value){ return value + 1; }; int aValue = 42; int incremented = increment(42); assert(incremented == 43); assert(aValue == 42)
  • 25. Type Inference // Does not compile auto add(auto first, auto second){ return first + second; } // Works for any two values that have operator+ defined auto add = [](const auto& first, const auto& second){ return first + second; };
  • 26. Value Capture Lambdas can capture values from the context. TEST_CASE(”type inference with lambdas”){ int first = 5; auto add = [=](const auto& second){ return first + second; }; CHECK_EQ(42, add(37)); CHECK_EQ(42.5, add(37.5)); }
  • 28. Consequences Functions are data. We can do operations on data. We can do operations on functions!
  • 30. What is an Operation on Functions? Any operation that takes one (or more functions) and returns a new function. • Partial Application • Functional Composition • Currying • Higher level functions
  • 31. Partial Application A function with n-1 parameters is obtained from a function with n parameters by binding one parameter to a value. using namespace std::placeholders; auto divide = [](const auto& first, const auto& second){ return first/second; }; int specialValue = 10; auto divideSpecialValue = bind(divide, specialValue, _1); // Equivalent with // auto divideSpecialValue = [](const auto& second) { // return 10 / second // };
  • 32. Functional Composition Create a function h(x) from two functions f(y) and g(z), such that for any value of x, h(x) = f(g(x)). C++ doesn’t yet have a functional composition operator, so we have to write our own function: template<typename F, typename G> auto compose(F f, G g){ return [f, g](auto x){ return f(g(x)); }; }
  • 33. Example auto increment = [](const auto& value){ return value + 1; }; auto incrementTwice = compose(increment, increment); /* Equivalent with: auto incrementTwice = [&](const auto& value){ return increment(increment(value)); }; */ CHECK_EQ(3, incrementTwice(1));
  • 34. Currying Decompose a function with N arguments into N functions with one argument auto curriedAdd = [](const auto& first){ return [first](const auto& second){ return first + second; }; };
  • 35. Currying in C++ Unfortunately, there’s no operator that supports currying. In pure functional languages, curry is done by default, and linked with partial application. For example: auto divide = [](const auto& first, const auto& second){ return first/second; }; divide(5) => a new function that takes second as parameter, equ
  • 37. Pass Functions as Parameters TEST_CASE(”pass functions as parameters”){ vector<int> values{42, 1, 55, 23}; vector<int> expected{1, 23, 42, 55}; auto compare = [](const auto& first, const auto& second){ return (first < second); }; sort(values.begin(), values.end(), compare); CHECK_EQ(expected, values); }
  • 38. Short list of higher level functions Find them in or • find_if • transform • reduce / accumulate • count_if • all_of / any_of / none_of • … See examples on https://github.com/MozaicWorks/functionalCpp
  • 40. Conclusions We can create functions from other functions through partial application, composition, currying. We can understand better the functions we write due to immutability.
  • 42. Problem: TicTacToe Result Given a TicTacToe board that’s either empty or already has moves, print out the result of the game if the game ended or that the game is still in progress.
  • 43. Approach 1. Clearly define the input; give examples 2. Clearly define the output; give examples 3. Identify a chain of functional transformations you can apply on the input data to turn it into the output data
  • 44. Clearly Define the Output • Game not started • Game in progress • X won • O won • Draw
  • 45. Clearly Define the Input Empty Board: _ _ _ _ _ _ _ _ _ X won by line: X X X O O _ _ _ _ etc.
  • 46. Turns out that … X wins if • any line is filled with X OR • any column is filled with X OR • the main diagonal is filled with X OR • the secondary diagonal is filled with X
  • 47. Transformations board -> collection(all lines, all columns, all diagonals) -> if any(collection, filledWithX) -> X won where filledWithX(line|column|diagonal L) = all(token on L equals 'X')
  • 48. Remove duplication with functional operators • Functions with the same parameter? Partial application! Or classes! • Functions with the same structure? Higher level functions! • Chained calls? Function composition!
  • 51. Refactoring code through Immutability Premise: • Any program can be written as Input -> Pure Functions -> State change (either UI or storage) • This property of the code applies on multiple levels, even on a single function
  • 52. Refactoring Method • Take a complex piece of code: • extract a small piece of it as another method • extract everything mutable as parameter • until the method is immutable • check by making everything const and compiling • then decompose the long immutable function into smaller immutable functions • then recombine the functions into classes, based on the parameters they use
  • 53. We End Up With Functional OOP • Data structures with set / get or public data • “Processor” objects that receive data and return other data • “Run and forget” objects: initialize, execute operations, throw it away • Separate, pluggable, input / output objects
  • 54. Hypothesis Unconfirmed Hypothesis: this type of refactoring is safe even without tests. (Or, we can easily generate tests for the immutable function with property-based testing)
  • 55. Conclusion Immutability and functions as data can simplify programming I invite you to try them out. Pick one and try it.
  • 56. Learn more Functional programming in C++: https: //www.slideshare.net/alexboly/functional-programming-in-c-88970494 Hidden loops: https://www.slideshare.net/alexboly/hidden-loops Removing structural duplication: https://www.slideshare.net/alexboly/removing-structuralduplication
  • 57. Learn more at Mozaic Works workshops https://mozaicworks.com/training/c-plus-plus/
  • 58. Pre-order my book! Hands-on Functional Programming In C++ - http://bit.ly/FProgCpp