SlideShare ist ein Scribd-Unternehmen logo
1 von 64
Downloaden Sie, um offline zu lesen
Functional programming in C++
Alex Bolboacă,  @alexboly,  alex.bolboaca@mozaicworks.com
February 2018
Intro
A practical view on functional programming
Mindset
Core Building Blocks
Improve design with functional programming
Bad design with functional programming
OOP and functional programming
Conclusions
Intro
Why I care about functional programming
I identify with the software craft movement
Learning & Improving
I want to learn as much as possible about my craft.
The evolution of the software industry is just recycling old ideas, and
functional programming is old.
All programming languages support functional constructs today.
More restrictions on code (eg. immutability) lead to better code and better
designs.
Disclaimer
I am an enthusiast, not an expert
Disclaimer
The code on the slides may be simplified for presentation purpose.
Find the valid examples on github: https://github.com/alexboly and
https://github.com/MozaicWorks
My First Touch of Functional Programming
(defun sqrt-iter (guess x)
(if (good-enough-p guess x)
guess
(sqrt-iter (improve guess x) x)))
Source: Professor Forrest Young, Psych 285
What is a monad?
The essence of monad is thus separation of
composition timeline from the composed
computation’s execution timeline, as well as the ability
of computation to implicitly carry extra data, as
pertaining to the computation itself, in addition to its
one (hence the name) output, that it will produce when
run (or queried, or called upon).
Source: https://wiki.haskell.org/Monad
A shorter explanation
All told, a monad in X is just a monoid in the category
of endofunctors of X, with product × replaced by
composition of endofunctors and unit set by the
identity endofunctor.
Saunders Mac Lane, “Categories for the Working Mathematician”
But don’t worry, just learn Category Theory
Category theory formalizes mathematical structure
and its concepts in terms of a labeled directed graph
called a category, whose nodes are called objects, and
whose labelled directed edges are called arrows (or
morphisms). A category has two basic properties: the
ability to compose the arrows associatively and the
existence of an identity arrow for each object.
…
Category theory has practical applications in
programming language theory, for example the usage
of monads in functional programming.
Wikipedia
Only one reaction
Whyyyyyyyyyyyyy?
A practical view on functional
programming
What I thought it was:
A way of writing unreadable code with many parantheses, with a strange
order of operations, in a community that likes complicated explanations
How I understand it now:
A style of software design that focuses on functions and immutability to
simplify code, to allow removal of certain types of duplication, and to show
intent better
Mindset
OOP
Design the objects and interactions between them
Key idea: message passing
Functional programming
Start from input data and apply a set of transformations to get it to the
desired output.
Key ideas: pure data structures and pure functions
Example 1: increment all elements of a list
Structured programming:
incrementAllElements(list& aList){
for(int i = 0; i < aList.size(); ++i){
aList[i] ++;
}
}
Functional programming:
//Simplified C++ code
transform(aList, [](const int item){ return item + 1 });
Example 2: Get a string with 5 ‘t’ characters
Structured programming:
string result;
for(int i = 0; i < 5; ++i){
result += ’t’;
}
Example 2 (cont’d)
Functional programming:
// Data in: a range from 1 to 5
// Data out: a string with 5 ’t’
// Transformations: transform each element from range
// to ’t’(map), then join them (reduce)
// Groovy code
[1..5].collect{’t’}.join()
// C++ doesn’t support it yet, except for boost
// Simplified C++ code using boost’s irange
transform(irange(1, 5), [](){return ’t’;});
Example 3: Pacman moves on a line to the right
OOP
Let’s create classes for: Pacman, Board, Wall, Dot, Movement etc.
Example 3 (cont’d)
Functional programming
Data in: a line with pacman on it
……>……
Data out: a line with pacman moving one square to the right, and a missing
dot
…… >…..
Transformations:
• Get everything before pacman
• Get everything after pacman
• Create a new line formed from: everything before pacman, an empty
space, pacman, everything after pacman except first element
Example 3 (cont’d)
const Line tick(const Line& initialLine){
return (
beforePacman(initialLine) +
KindOfToken::Empty +
KindOfToken::Pacman +
removeFirst(afterPacman(initialLine))
);
}
Full example at: https://github.com/alexboly/pacmanCpp/
Conclusion
FP mindset: Data in -> Transformations -> Data out
Each transformation is a pure function, except at the edge of the system
(I/O).
Core Building Blocks
Pure functions
A function that returns the same output whenever receiving the same input
In C++ const is your friend
Example: Not pure function
list.insert(5); // throws exception if too many elements
// otherwise, adds 5 to the list
Example: Pure function
const list insert(const list& aList, const int value) { ... };
newList = insert(aList, 5);
// always has the same behavior
// when passing in the same arguments
// unless externalities (eg. memory is full)
// Immutability!
Example: Immutable data structures
Immutable C++ example: https://github.com/rsms/immutable-cpp
auto a = Array<int>::empty();
a = a->push(1);
a = a->push(2);
a = a->push(3);
Lambdas / Anonymous functions
// Lambda variable
auto increment = [](auto value){return value + 1;};
assert(increment(2) == 3);
Lambda variable with specific captured context
int valueFromContext = 10;
auto appendValueFromContext =
[const auto valueFromContext](auto value){
return value + valueFromContext;
};
assert(appendValueFromContext(10) == 20);
Lambda variable capturing all used variables by copy
int valueFromContext = 10;
auto appendValueFromContext =
[=](auto value){
return value + valueFromContext;
};
assert(appendValueFromContext(10) == 20);
More details:
http://en.cppreference.com/w/cpp/language/lambda
Chaining functions
listOf3Elements = add(add(add(emptyList, 1), 2), 3);
Curry
Not this curry!
Curry. Haskell Curry.
Curry. Haskell Curry
Currying
// Without curry
list = add(list, 5);
list = add(list, 1000);
// With curry (bind in C++ 11)
auto addToEmptyList = bind(add, list<int>(), _1);
assert addToEmptyList(5) == list<int>({5});
assert addToEmptyList(1000) == list<int>({1000});
Functional composability
auto threeElementsList = [](int first, int second, int third){
return add(add(addToEmptyList(first), second), third);
};
// In some programming languages,
// composing functions has its own syntax
// Eg. Groovy
def oneElementList = add << addToEmptyList
// same as add(addToEmptyList(), _)
assert(threeElementsList(0, 1, 2) == list<int>({0, 1, 2}));
Currying and composability
auto addTwoElementsToEmptyList = [](const int first, const int
return add(addToEmptyList(first), second);
};
auto listWith0And1 = bind(addTwoElementsToEmptyList, 0, 1);
assert(listWith0And1() == list<int>({0, 1});
Higher level functionvalues
We can pass functions as parameters
auto incrementFunctionResult = [](const auto aFunction){
return aFunction() + 1;
};
auto function1 = [](){
return 1;
};
assert(incrementFunctionResult(function1) == 2);
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
Almost anything can be a function
//TRUE = {x -> { y -> x}}
auto TRUE = [](auto x){
return [x](auto y){
return x;
};
};
//FALSE = {x -> { y -> y}}
auto FALSE = [](auto x){
return [](auto y){
return y;
};
};
Church encoding for booleans (cont’d)
//IF = {proc -> { x -> { y -> proc(x)(y) }}}
auto IF = [](auto proc){
return [proc](auto x){
return [x, proc](auto y){
return proc(x)(y);
};
};
};
CHECK(IF(TRUE)(”foo”)(”bar”) == ”foo”);
Source: https://github.com/alexboly/ChurchEncodingCpp
Conclusions
• Pure functions are the basic building blocks of functional programming
• The best functions are small and polymorphic
• When the same parameter is passed to multiple function calls,
consider using curry (bind in C++)
• When the return of a function is passed to another function multiple
times, consider using functional composition
• Reuse existing functions as much as possible: map (transform in C++),
reduce, find etc.
• Experiment with functional programming: TicTacToe score, pacman,
tetris
• Replace traditional loops with functional loops as much as possible
Improve design with functional
programming
Clarify loops intent
for(auto element=list.begin(); element != list.end(); element++
// I have to read all of this to understand what the loop does
}
Functional loops
transform(....); // transform a collection into another!
auto increment = [](auto value){return value + 1;};
transform(list, increment); // transform a list into another
// with incremented elements
transform(list, increment); // compute the sum
// of all incremented elements
// compute the sum of all incremented even numbers
reduce(find(transform(list, increment), evenNumber), plus)
What about web apps?
Data in: an HTTP request
Data out: HTML + a response code + something saved in a store
Transformations:
• validation
• sanitization
• canonicalization
• business rules
• save to database (mutable!)
• or read from database (mutable!)
• convert to view
• pass on to html rendering
Everything in between request and database, and database and response,
is immutable!
Bad design with functional
programming
Abstract functions != Readability
computeNextBoardOnAxis(board, currentAxis, nextAxis) {
def movableTokensForAxis = KindOfToken.values().findAll {
it.axis == nextAxis && it.isMovable
}
def rotateForward = { aBoard ->
rotateBoardOnAxis(aBoard, currentAxis, nextAxis)
}
def rotateBack = { aBoard ->
rotateBoardOnAxis(aBoard, currentAxis, nextAxis)
}
return rotateBack(
computeNewBoard(rotateForward(board),
movableTokensForAxis
))
}
My ugly code
def createCertificate(self, attendeeText, fileName):
imageOpenOperation = OpenImageOperation(self.baseImagePath)
attendeeTextWriteOperation = TextWriteImageOperation(attend
courseTextWriteOperation = TextWriteImageOperation(self.cou
dateTextWriteOperation = TextWriteImageOperation(self.dateT
signatureOverlayOperation = ImageOverlayOperation(self.trai
filters = ImageOperations([imageOpenOperation,
attendeeTextWriteOperation, courseTextWriteOperation,
dateTextWriteOperation, signatureOverlayOperation])
filters.execute(fileName)
return fileName
class TextWriteImageOperation:
def __init__(self, text):
self.text = text
def execute(self, image):
draw = ImageDraw.Draw(image)
textPositionX = self.__getXPositionForCenteredText(
if self.text.shouldCenter()
else self.text.column()
self.__drawText(draw, textPositionX)
del draw
return image;
OOP and functional programming
Relationship between OOP and functional programming
A class is nothing more than a set of cohesive, partially applied pure
functions
– via JB Rainsberger
Remember first example?
// OOP version: Cohesion
class List{
private listStorage
add(element){....}
removeLast(){....}
}
// Functional version
add(list, element)
removeLast(list)
// Equivalence
def add = [](auto listStorage, auto element){return ....};
// For oop bind function parameters
// to the data members of the class
auto oopAdd = [](element){ return add(initialListStorage, eleme
// Or curry (bind)
def oopAdd = bind(add, initialListStorage)
oopAdd(5)
Conclusions
My thoughts
Good:
• Functional programming mindset is very useful for data-centric
applications
• Higher level functions simplify and clarify intent for data
transformations
• Pure functions are very easy to test
• Clear separation between mutable and immutable state simplifies
everything
Careful:
• Beware of too high abstraction & ensure your colleagues understand
the code
• Carefully mix OOP with functional constructs
Can’t ignore:
• Functional programming is here to stay due to CPUs going multicore
• New applications: big data, reactive programming etc.
• All modern languages have FP constructs built in
• Clojure, Scala, Haskell, F# are used and will be used
• AI is built using FP (composability)
Learn more
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/
Thank you!
I’ve been Alex Bolboacă, @alexboly, alex.bolboaca@mozaicworks.com
programmer, trainer, mentor, writer
at Mozaic Works
Think. Design. Work Smart.
https://mozaicworks.com
Q&A
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Omar Abdelhafith
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts Pavan Babu .G
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBryan O'Sullivan
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in PythonSujith Kumar
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scalaPiotr Paradziński
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Reuven Lerner
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonAnoop Thomas Mathew
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingJordan Parmer
 

Was ist angesagt? (20)

Python basics
Python basicsPython basics
Python basics
 
Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)Introduction to functional programming (In Arabic)
Introduction to functional programming (In Arabic)
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
F# 101
F# 101F# 101
F# 101
 
Phyton Learning extracts
Phyton Learning extracts Phyton Learning extracts
Phyton Learning extracts
 
BayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore HaskellBayFP: Concurrent and Multicore Haskell
BayFP: Concurrent and Multicore Haskell
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 
Regular expressions in Python
Regular expressions in PythonRegular expressions in Python
Regular expressions in Python
 
Contravariant functors in scala
Contravariant functors in scalaContravariant functors in scala
Contravariant functors in scala
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Python basic
Python basicPython basic
Python basic
 
Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014Functional Python Webinar from October 22nd, 2014
Functional Python Webinar from October 22nd, 2014
 
Matlab python-
Matlab python-Matlab python-
Matlab python-
 
Thinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in PythonThinking in Functions: Functional Programming in Python
Thinking in Functions: Functional Programming in Python
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Scientific Python
Scientific PythonScientific Python
Scientific Python
 
Python Basics
Python BasicsPython Basics
Python Basics
 

Ähnlich wie FP TITLE

1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?UFPA
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and BeyondComicSansMS
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...PVS-Studio
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#Talbott Crowell
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional ProgrammingYuan Wang
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Bryan O'Sullivan
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 

Ähnlich wie FP TITLE (20)

Functions in c++
Functions in c++Functions in c++
Functions in c++
 
CPP Assignment Help
CPP Assignment HelpCPP Assignment Help
CPP Assignment Help
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Cpp17 and Beyond
Cpp17 and BeyondCpp17 and Beyond
Cpp17 and Beyond
 
The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...The use of the code analysis library OpenC++: modifications, improvements, er...
The use of the code analysis library OpenC++: modifications, improvements, er...
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
C++ Programming
C++ ProgrammingC++ Programming
C++ Programming
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Programming Assignment Help
Programming Assignment HelpProgramming Assignment Help
Programming Assignment Help
 
Functions
FunctionsFunctions
Functions
 
Exploring SharePoint with F#
Exploring SharePoint with F#Exploring SharePoint with F#
Exploring SharePoint with F#
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Real World Haskell: Lecture 1
Real World Haskell: Lecture 1Real World Haskell: Lecture 1
Real World Haskell: Lecture 1
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 

Mehr von Alexandru Bolboaca

Mehr von 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
 

Kürzlich hochgeladen

Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
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
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
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
 
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
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
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
 
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
 
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
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
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
 
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
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
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
 
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
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
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
 

Kürzlich hochgeladen (20)

Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
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...
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
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)
 
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 - ...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
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
 
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
 
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
 
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
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
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
 
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
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
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
 
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...
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
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
 

FP TITLE

  • 1. Functional programming in C++ Alex Bolboacă,  @alexboly,  alex.bolboaca@mozaicworks.com February 2018
  • 2. Intro A practical view on functional programming Mindset Core Building Blocks Improve design with functional programming Bad design with functional programming OOP and functional programming Conclusions
  • 4. Why I care about functional programming I identify with the software craft movement
  • 5. Learning & Improving I want to learn as much as possible about my craft. The evolution of the software industry is just recycling old ideas, and functional programming is old. All programming languages support functional constructs today. More restrictions on code (eg. immutability) lead to better code and better designs.
  • 6. Disclaimer I am an enthusiast, not an expert
  • 7. Disclaimer The code on the slides may be simplified for presentation purpose. Find the valid examples on github: https://github.com/alexboly and https://github.com/MozaicWorks
  • 8. My First Touch of Functional Programming (defun sqrt-iter (guess x) (if (good-enough-p guess x) guess (sqrt-iter (improve guess x) x))) Source: Professor Forrest Young, Psych 285
  • 9. What is a monad? The essence of monad is thus separation of composition timeline from the composed computation’s execution timeline, as well as the ability of computation to implicitly carry extra data, as pertaining to the computation itself, in addition to its one (hence the name) output, that it will produce when run (or queried, or called upon). Source: https://wiki.haskell.org/Monad
  • 10. A shorter explanation All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor. Saunders Mac Lane, “Categories for the Working Mathematician”
  • 11. But don’t worry, just learn Category Theory Category theory formalizes mathematical structure and its concepts in terms of a labeled directed graph called a category, whose nodes are called objects, and whose labelled directed edges are called arrows (or morphisms). A category has two basic properties: the ability to compose the arrows associatively and the existence of an identity arrow for each object. … Category theory has practical applications in programming language theory, for example the usage of monads in functional programming. Wikipedia
  • 13. A practical view on functional programming
  • 14. What I thought it was: A way of writing unreadable code with many parantheses, with a strange order of operations, in a community that likes complicated explanations
  • 15. How I understand it now: A style of software design that focuses on functions and immutability to simplify code, to allow removal of certain types of duplication, and to show intent better
  • 17. OOP Design the objects and interactions between them Key idea: message passing
  • 18. Functional programming Start from input data and apply a set of transformations to get it to the desired output. Key ideas: pure data structures and pure functions
  • 19. Example 1: increment all elements of a list Structured programming: incrementAllElements(list& aList){ for(int i = 0; i < aList.size(); ++i){ aList[i] ++; } } Functional programming: //Simplified C++ code transform(aList, [](const int item){ return item + 1 });
  • 20. Example 2: Get a string with 5 ‘t’ characters Structured programming: string result; for(int i = 0; i < 5; ++i){ result += ’t’; }
  • 21. Example 2 (cont’d) Functional programming: // Data in: a range from 1 to 5 // Data out: a string with 5 ’t’ // Transformations: transform each element from range // to ’t’(map), then join them (reduce) // Groovy code [1..5].collect{’t’}.join() // C++ doesn’t support it yet, except for boost // Simplified C++ code using boost’s irange transform(irange(1, 5), [](){return ’t’;});
  • 22. Example 3: Pacman moves on a line to the right OOP Let’s create classes for: Pacman, Board, Wall, Dot, Movement etc.
  • 23. Example 3 (cont’d) Functional programming Data in: a line with pacman on it ……>…… Data out: a line with pacman moving one square to the right, and a missing dot …… >….. Transformations: • Get everything before pacman • Get everything after pacman • Create a new line formed from: everything before pacman, an empty space, pacman, everything after pacman except first element
  • 24. Example 3 (cont’d) const Line tick(const Line& initialLine){ return ( beforePacman(initialLine) + KindOfToken::Empty + KindOfToken::Pacman + removeFirst(afterPacman(initialLine)) ); } Full example at: https://github.com/alexboly/pacmanCpp/
  • 25. Conclusion FP mindset: Data in -> Transformations -> Data out Each transformation is a pure function, except at the edge of the system (I/O).
  • 27. Pure functions A function that returns the same output whenever receiving the same input In C++ const is your friend
  • 28. Example: Not pure function list.insert(5); // throws exception if too many elements // otherwise, adds 5 to the list
  • 29. Example: Pure function const list insert(const list& aList, const int value) { ... }; newList = insert(aList, 5); // always has the same behavior // when passing in the same arguments // unless externalities (eg. memory is full) // Immutability!
  • 30. Example: Immutable data structures Immutable C++ example: https://github.com/rsms/immutable-cpp auto a = Array<int>::empty(); a = a->push(1); a = a->push(2); a = a->push(3);
  • 31. Lambdas / Anonymous functions // Lambda variable auto increment = [](auto value){return value + 1;}; assert(increment(2) == 3);
  • 32. Lambda variable with specific captured context int valueFromContext = 10; auto appendValueFromContext = [const auto valueFromContext](auto value){ return value + valueFromContext; }; assert(appendValueFromContext(10) == 20);
  • 33. Lambda variable capturing all used variables by copy int valueFromContext = 10; auto appendValueFromContext = [=](auto value){ return value + valueFromContext; }; assert(appendValueFromContext(10) == 20); More details: http://en.cppreference.com/w/cpp/language/lambda
  • 34. Chaining functions listOf3Elements = add(add(add(emptyList, 1), 2), 3);
  • 37. Currying // Without curry list = add(list, 5); list = add(list, 1000); // With curry (bind in C++ 11) auto addToEmptyList = bind(add, list<int>(), _1); assert addToEmptyList(5) == list<int>({5}); assert addToEmptyList(1000) == list<int>({1000});
  • 38. Functional composability auto threeElementsList = [](int first, int second, int third){ return add(add(addToEmptyList(first), second), third); }; // In some programming languages, // composing functions has its own syntax // Eg. Groovy def oneElementList = add << addToEmptyList // same as add(addToEmptyList(), _) assert(threeElementsList(0, 1, 2) == list<int>({0, 1, 2}));
  • 39. Currying and composability auto addTwoElementsToEmptyList = [](const int first, const int return add(addToEmptyList(first), second); }; auto listWith0And1 = bind(addTwoElementsToEmptyList, 0, 1); assert(listWith0And1() == list<int>({0, 1});
  • 40. Higher level functionvalues We can pass functions as parameters auto incrementFunctionResult = [](const auto aFunction){ return aFunction() + 1; }; auto function1 = [](){ return 1; }; assert(incrementFunctionResult(function1) == 2);
  • 41. 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
  • 42. Almost anything can be a function //TRUE = {x -> { y -> x}} auto TRUE = [](auto x){ return [x](auto y){ return x; }; }; //FALSE = {x -> { y -> y}} auto FALSE = [](auto x){ return [](auto y){ return y; }; };
  • 43. Church encoding for booleans (cont’d) //IF = {proc -> { x -> { y -> proc(x)(y) }}} auto IF = [](auto proc){ return [proc](auto x){ return [x, proc](auto y){ return proc(x)(y); }; }; }; CHECK(IF(TRUE)(”foo”)(”bar”) == ”foo”); Source: https://github.com/alexboly/ChurchEncodingCpp
  • 44. Conclusions • Pure functions are the basic building blocks of functional programming • The best functions are small and polymorphic • When the same parameter is passed to multiple function calls, consider using curry (bind in C++) • When the return of a function is passed to another function multiple times, consider using functional composition • Reuse existing functions as much as possible: map (transform in C++), reduce, find etc. • Experiment with functional programming: TicTacToe score, pacman, tetris • Replace traditional loops with functional loops as much as possible
  • 45. Improve design with functional programming
  • 46. Clarify loops intent for(auto element=list.begin(); element != list.end(); element++ // I have to read all of this to understand what the loop does }
  • 47. Functional loops transform(....); // transform a collection into another! auto increment = [](auto value){return value + 1;}; transform(list, increment); // transform a list into another // with incremented elements transform(list, increment); // compute the sum // of all incremented elements // compute the sum of all incremented even numbers reduce(find(transform(list, increment), evenNumber), plus)
  • 48. What about web apps? Data in: an HTTP request Data out: HTML + a response code + something saved in a store Transformations: • validation • sanitization • canonicalization • business rules • save to database (mutable!) • or read from database (mutable!) • convert to view • pass on to html rendering Everything in between request and database, and database and response, is immutable!
  • 49. Bad design with functional programming
  • 50. Abstract functions != Readability computeNextBoardOnAxis(board, currentAxis, nextAxis) { def movableTokensForAxis = KindOfToken.values().findAll { it.axis == nextAxis && it.isMovable } def rotateForward = { aBoard -> rotateBoardOnAxis(aBoard, currentAxis, nextAxis) } def rotateBack = { aBoard -> rotateBoardOnAxis(aBoard, currentAxis, nextAxis) } return rotateBack( computeNewBoard(rotateForward(board), movableTokensForAxis )) }
  • 51. My ugly code def createCertificate(self, attendeeText, fileName): imageOpenOperation = OpenImageOperation(self.baseImagePath) attendeeTextWriteOperation = TextWriteImageOperation(attend courseTextWriteOperation = TextWriteImageOperation(self.cou dateTextWriteOperation = TextWriteImageOperation(self.dateT signatureOverlayOperation = ImageOverlayOperation(self.trai filters = ImageOperations([imageOpenOperation, attendeeTextWriteOperation, courseTextWriteOperation, dateTextWriteOperation, signatureOverlayOperation]) filters.execute(fileName) return fileName
  • 52. class TextWriteImageOperation: def __init__(self, text): self.text = text def execute(self, image): draw = ImageDraw.Draw(image) textPositionX = self.__getXPositionForCenteredText( if self.text.shouldCenter() else self.text.column() self.__drawText(draw, textPositionX) del draw return image;
  • 53. OOP and functional programming
  • 54. Relationship between OOP and functional programming A class is nothing more than a set of cohesive, partially applied pure functions – via JB Rainsberger
  • 55. Remember first example? // OOP version: Cohesion class List{ private listStorage add(element){....} removeLast(){....} } // Functional version add(list, element) removeLast(list)
  • 56. // Equivalence def add = [](auto listStorage, auto element){return ....}; // For oop bind function parameters // to the data members of the class auto oopAdd = [](element){ return add(initialListStorage, eleme // Or curry (bind) def oopAdd = bind(add, initialListStorage) oopAdd(5)
  • 58. My thoughts Good: • Functional programming mindset is very useful for data-centric applications • Higher level functions simplify and clarify intent for data transformations • Pure functions are very easy to test • Clear separation between mutable and immutable state simplifies everything
  • 59. Careful: • Beware of too high abstraction & ensure your colleagues understand the code • Carefully mix OOP with functional constructs
  • 60. Can’t ignore: • Functional programming is here to stay due to CPUs going multicore • New applications: big data, reactive programming etc. • All modern languages have FP constructs built in • Clojure, Scala, Haskell, F# are used and will be used • AI is built using FP (composability)
  • 61. Learn more Hidden loops: https://www.slideshare.net/alexboly/hidden-loops Removing structural duplication: https://www.slideshare.net/ alexboly/removing-structuralduplication
  • 62. Learn more at Mozaic Works workshops https://mozaicworks.com/training/c-plus-plus/
  • 63. Thank you! I’ve been Alex Bolboacă, @alexboly, alex.bolboaca@mozaicworks.com programmer, trainer, mentor, writer at Mozaic Works Think. Design. Work Smart. https://mozaicworks.com