SlideShare a Scribd company logo
1 of 59
Download to read offline
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

What's hot

Function class in c++
Function class in c++Function class in c++
Function class in c++Kumar
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKamal Acharya
 
Functions in c++
Functions in c++Functions in c++
Functions in c++Maaz Hasan
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)Jay Patel
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++Learn By Watch
 

What's hot (17)

Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Inline function
Inline functionInline function
Inline function
 
Beyond Mere Actors
Beyond Mere ActorsBeyond Mere Actors
Beyond Mere Actors
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
3d7b7 session4 c++
3d7b7 session4 c++3d7b7 session4 c++
3d7b7 session4 c++
 
Lecture5
Lecture5Lecture5
Lecture5
 
Inline functions
Inline functionsInline functions
Inline functions
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
Inline function(oops)
Inline function(oops)Inline function(oops)
Inline function(oops)
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 

Similar to Thinking in Functions

Similar to Thinking in Functions (20)

Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functional programming in C++
Functional programming in C++Functional programming in C++
Functional programming in C++
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
C++ unit-1-part-11
C++ unit-1-part-11C++ unit-1-part-11
C++ unit-1-part-11
 
#Code2 create c++ for beginners
#Code2 create  c++ for beginners #Code2 create  c++ for beginners
#Code2 create c++ for beginners
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
ACM init()- Day 4
ACM init()- Day 4ACM init()- Day 4
ACM init()- Day 4
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 
arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 

More from Alexandru Bolboaca

More from Alexandru Bolboaca (20)

Refactor legacy code through pure functions
Refactor legacy code through pure functionsRefactor legacy code through pure functions
Refactor legacy code through pure functions
 
Design Without Types
Design Without TypesDesign Without Types
Design Without Types
 
Raising the Bar
Raising the BarRaising the Bar
Raising the Bar
 
The Journey to Master Code Design
The Journey to Master Code DesignThe Journey to Master Code Design
The Journey to Master Code Design
 
What is good software design? And why it matters?
What is good software design? And why it matters?What is good software design? And why it matters?
What is good software design? And why it matters?
 
Agile Technical Leadership
Agile Technical LeadershipAgile Technical Leadership
Agile Technical Leadership
 
TDD As If You Meant It
TDD As If You Meant ItTDD As If You Meant It
TDD As If You Meant It
 
Usable Software Design
Usable Software DesignUsable Software Design
Usable Software Design
 
Hidden loops
Hidden loopsHidden loops
Hidden loops
 
Removing structural duplication
Removing structural duplicationRemoving structural duplication
Removing structural duplication
 
Continuous delivery
Continuous deliveryContinuous delivery
Continuous delivery
 
Why You Should Start Using Docker
Why You Should Start Using DockerWhy You Should Start Using Docker
Why You Should Start Using Docker
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
Applied craftsmanship
Applied craftsmanshipApplied craftsmanship
Applied craftsmanship
 
Pyramid of-developer-skills
Pyramid of-developer-skillsPyramid of-developer-skills
Pyramid of-developer-skills
 
Stay focused
Stay focusedStay focused
Stay focused
 
Kanban intro
Kanban introKanban intro
Kanban intro
 
Unit testing-patterns
Unit testing-patternsUnit testing-patterns
Unit testing-patterns
 
Incremental design, simply explained
Incremental design, simply explainedIncremental design, simply explained
Incremental design, simply explained
 
Exploring design-alternatives-using-tdd
Exploring design-alternatives-using-tddExploring design-alternatives-using-tdd
Exploring design-alternatives-using-tdd
 

Recently uploaded

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
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
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
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
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
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
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
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
 
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
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
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
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
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)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
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
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
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
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
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
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
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...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
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
 
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
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
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...
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
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
 

Thinking in Functions

  • 1. Thinking In Functions Alex Bolboacă,  @alexboly,  alex.bolboaca@mozaicworks.com 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