SlideShare a Scribd company logo
1 of 28
Download to read offline
Categories for the
Working C++ Programmer
Bartosz Milewski
Moscow, Feb 2015
The Essence of Programming
• Composition
• Problem Solving: Decomposition
• Coding: Re-composition
Low Level/High Level
Category
• Embarrassingly simple concept
• Objects
• Arrows between objects
Composition
• Arrow from A to B. f :: A → B
• Arrow from B to C. g :: B → C
• Composition, g after f. g ∘ f :: A → C!
• Associativity. (f ∘ g) ∘ h = f ∘(g ∘ h)
Identity
• For every object A
• id :: A → A!
• f :: A → B!
f ∘ id = f!
• g :: B → A!
id ∘ g = g
Monoid
• Embarrassingly simple concept
• One object M
• Arrows f :: M → M!
• All arrows composable
• One identity arrow
Examples
• Addition + 0
• Multiplication * 1
• String concatenation + “”
• Logging, Gathering Data, Auditing
Types and Functions
• Set: category of sets and functions
• Objects: Types = Sets of values
• Arrows: Functions from one type to another
• Composition
C g_after_f(A x) {
B y = f(x);
return g(y);
}
Pure Functions
• No side effects
• When called with same arguments, returns same
values (referential transparency)
• Can be memoized
• The only dependencies in code are through
composition
Side Effects
• Simplest example: auditing
• Sequence of functions
• getKey(password)->key
• withdraw(key)->money
• Each function leaves audit trail
Global Auditor
string audit;
!
int logIn(string passwd){
audit += passwd;
return 42;
}
!
double withdraw(int key){
audit += “withdrawing ”;
return 100.0;
}
• Poor scaling, maintenance, flexibility
In/Out Auditor
pair<int, string>
logIn(string passwd, string audit){
return make_pair(42, audit + passwd);
}
!
pair<double, string>
withdraw(int key, string audit){
return make_pair(100.0
, audit + “withdrawing ”);
}
• Doesn’t memoize well
• Each function has access to full log and
must know how to accumulate data
Out Auditor
pair<int, string>
logIn(string passwd){
return make_pair(42, passwd);
}
!
pair<double, string>
withdraw(int key){
return make_pair(100.0
,“withdrawing ”);
}
• Each function responsible only for its data
• But how to compose such functions?
Writer
template<class A>
using Writer = pair<A, string>;
Writer<int> logIn(string passwd){
return make_pair(42, passwd);
}
!
Writer<double> withdraw(int key){
return make_pair(100.0
,“withdrawing ”);
}
• How to compose?
Composition
Writer<double> transact(string passwd){
auto p1 logIn(passwd);
auto p2 withdraw(p1.first);
return make_pair(p2.first
, p1.second + p2.second);
}
• Audit trail accumulated “between” calls
Abstracting Composition
template<class A, class B, class C>
function<Writer<C>(A)>
compose(function<Writer<B>(A)> f
,function<Writer<C>(B)> g)
{
return [f, g](A x) {
auto p1 = f(x);
auto p2 = g(p1.first);
return make_pair(p2.first
, p1.second + p2.second);
};
}
• Composing two functions using a higher order function
Using Composition
Writer<double> transact(string passwd){
return compose<string, int, double>
(logIn, withdraw)(passwd);
}
• Between calls
• Explicit type annotations
Type Inference
auto const compose = [](auto f, auto g) {
return [f, g](auto x) {
auto p1 = f(x);
auto p2 = g(p1.first);
return make_pair(p2.first
, p1.second + p2.second);
};
};
• C++14 generalized lambdas with return type deduction
Objects, Arrows, Composition
• Objects: Data Types
• Arrows: (Pure) Functions
• Composition: result of one function = argument of
another function
C g_after_f(A x) {
B y = f(x);
return g(y);
}
Category of Embellished
Functions
• Objects = types like A, B, C
• Arrow from A to B = function from A to some type that depends
on B (Embellished type)
• For instance: pair<A, string> (or Writer<A>)
• Composition:
• f :: A → pair<B, string>
• g :: B → pair<C, string>
• g ∘ f :: A → pair<C, string>
Kleisli Category
template<class A>
Writer<A> identity(A x) {
return make_pair(x, "");
}
auto const compose = [](auto f, auto g) {
return [f, g](auto x) {
auto p1 = f(x);
auto p2 = g(p1.first);
return make_pair(p2.first
, p1.second + p2.second);
};
};
Controlling Side Effects
• Pure functions
• Side effects through composition
• Write your code using embellished functions
• Glue it using composition combinators
Does it Generalize?
• Writer generalizes to any monoid
• Embellishment = Categorical Functor
• Composition and identity for embellished functions
= monad
The Future Monad
• Embellished functions: functions returning
future<T>
• Composition through then
• Identity: make_ready_future
Resumable Functions
int cnt = 0;
do
{
cnt = await streamR.read(512, buf);
if ( cnt == 0 ) break;
cnt = await streamW.write(cnt, buf);
} while (cnt > 0);
• Low level thinking: Coroutines, State
• High level: Hiding the glue
Resumable Generators
generator<int> fib()
{
int a = 0;
int b = 1;
for (;;) {
__yield_value a;
auto next = a + b;
a = b;
b = next;
}
}
• The same monadic pattern
The C++ Opportunity
• Grand Unification (Controlling side effects)
• Futures
• Ranges
• Exceptions
• Continuations
• User-defined monads

More Related Content

What's hot

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01Abdul Samee
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJTed Leung
 
김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011devCAT Studio, NEXON
 
03. operators and-expressions
03. operators and-expressions03. operators and-expressions
03. operators and-expressionsStoian Kirov
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersJayaram Sankaranarayanan
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
C++ overloading
C++ overloadingC++ overloading
C++ overloadingsanya6900
 
Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04IIUM
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programAAKASH KUMAR
 

What's hot (17)

3 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp013 operators-expressions-and-statements-120712073351-phpapp01
3 operators-expressions-and-statements-120712073351-phpapp01
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
 
College1
College1College1
College1
 
김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011김재석, C++ 프로그래머를 위한 C#, NDC2011
김재석, C++ 프로그래머를 위한 C#, NDC2011
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
03. operators and-expressions
03. operators and-expressions03. operators and-expressions
03. operators and-expressions
 
Polymorphismupload
PolymorphismuploadPolymorphismupload
Polymorphismupload
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Functional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 DevelopersFunctional Programming 101 for Java 7 Developers
Functional Programming 101 for Java 7 Developers
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
C++11
C++11C++11
C++11
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Csc1100 lecture04 ch04
Csc1100 lecture04 ch04Csc1100 lecture04 ch04
Csc1100 lecture04 ch04
 
c++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ programc++ programming Unit 2 basic structure of a c++ program
c++ programming Unit 2 basic structure of a c++ program
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 

Similar to Categories for the Working C++ Programmer

Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptBrendan Eich
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS ResponsibilitiesBrendan Eich
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]Emmanuel Nhan
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)Eduard Tomàs
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||Ashwin Rao
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Brendan Eich
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about CYi-Hsiu Hsu
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++Alexander Granin
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeManoj Kumar
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginnersophoeutsen2
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginnerskenbot
 

Similar to Categories for the Working C++ Programmer (20)

Extensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScriptExtensible Operators and Literals for JavaScript
Extensible Operators and Literals for JavaScript
 
Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
 
JS Responsibilities
JS ResponsibilitiesJS Responsibilities
JS Responsibilities
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]Functional programming in kotlin with Arrow [Sunnytech 2018]
Functional programming in kotlin with Arrow [Sunnytech 2018]
 
JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)JavaScript in 2016 (Codemotion Rome)
JavaScript in 2016 (Codemotion Rome)
 
JavaScript in 2016
JavaScript in 2016JavaScript in 2016
JavaScript in 2016
 
Introduction to c part 2
Introduction to c   part  2Introduction to c   part  2
Introduction to c part 2
 
The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||The Fuss about || Haskell | Scala | F# ||
The Fuss about || Haskell | Scala | F# ||
 
Thinking in Functions
Thinking in FunctionsThinking in Functions
Thinking in Functions
 
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)Value Objects, Full Throttle (to be updated for spring TC39 meetings)
Value Objects, Full Throttle (to be updated for spring TC39 meetings)
 
Understand more about C
Understand more about CUnderstand more about C
Understand more about C
 
The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++The Present and The Future of Functional Programming in C++
The Present and The Future of Functional Programming in C++
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 
C programming tutorial for Beginner
C programming tutorial for BeginnerC programming tutorial for Beginner
C programming tutorial for Beginner
 
Category theory for beginners
Category theory for beginnersCategory theory for beginners
Category theory for beginners
 
Constructor and destructor in C++
Constructor and destructor in C++Constructor and destructor in C++
Constructor and destructor in C++
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 

More from Platonov Sergey

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияPlatonov Sergey
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3Platonov Sergey
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Platonov Sergey
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеТененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеPlatonov Sergey
 
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxПавел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxPlatonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIPlatonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IPlatonov Sergey
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практикеPlatonov Sergey
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутовPlatonov Sergey
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Platonov Sergey
 
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Platonov Sergey
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийPlatonov Sergey
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Platonov Sergey
 
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Platonov Sergey
 
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияДракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияPlatonov Sergey
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьPlatonov Sergey
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыPlatonov Sergey
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузераPlatonov Sergey
 

More from Platonov Sergey (20)

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализация
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
 
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
Евгений Рыжков, Андрей Карпов Как потратить 10 лет на разработку анализатора ...
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговлеТененёв Анатолий, Boost.Asio в алгоритмической торговле
Тененёв Анатолий, Boost.Asio в алгоритмической торговле
 
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на LinuxПавел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
Павел Беликов, Опыт мигрирования крупного проекта с Windows-only на Linux
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практике
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутов
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++
 
C++ exceptions
C++ exceptionsC++ exceptions
C++ exceptions
 
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
Как мы уменьшили количество ошибок в Unreal Engine с помощью статического ана...
 
HPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычисленийHPX: C++11 runtime система для параллельных и распределённых вычислений
HPX: C++11 runtime система для параллельных и распределённых вычислений
 
Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08Ranges calendar-novosibirsk-2015-08
Ranges calendar-novosibirsk-2015-08
 
Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...Использование maven для сборки больших модульных c++ проектов на примере Odin...
Использование maven для сборки больших модульных c++ проектов на примере Odin...
 
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведенияДракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
Дракон в мешке: от LLVM к C++ и проблемам неопределенного поведения
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим жить
 
DI в C++ тонкости и нюансы
DI в C++ тонкости и нюансыDI в C++ тонкости и нюансы
DI в C++ тонкости и нюансы
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузера
 

Recently uploaded

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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
 
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
 

Recently uploaded (20)

Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
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
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

Categories for the Working C++ Programmer

  • 1. Categories for the Working C++ Programmer Bartosz Milewski Moscow, Feb 2015
  • 2. The Essence of Programming • Composition • Problem Solving: Decomposition • Coding: Re-composition
  • 4. Category • Embarrassingly simple concept • Objects • Arrows between objects
  • 5. Composition • Arrow from A to B. f :: A → B • Arrow from B to C. g :: B → C • Composition, g after f. g ∘ f :: A → C! • Associativity. (f ∘ g) ∘ h = f ∘(g ∘ h)
  • 6. Identity • For every object A • id :: A → A! • f :: A → B! f ∘ id = f! • g :: B → A! id ∘ g = g
  • 7. Monoid • Embarrassingly simple concept • One object M • Arrows f :: M → M! • All arrows composable • One identity arrow
  • 8. Examples • Addition + 0 • Multiplication * 1 • String concatenation + “” • Logging, Gathering Data, Auditing
  • 9. Types and Functions • Set: category of sets and functions • Objects: Types = Sets of values • Arrows: Functions from one type to another • Composition C g_after_f(A x) { B y = f(x); return g(y); }
  • 10. Pure Functions • No side effects • When called with same arguments, returns same values (referential transparency) • Can be memoized • The only dependencies in code are through composition
  • 11. Side Effects • Simplest example: auditing • Sequence of functions • getKey(password)->key • withdraw(key)->money • Each function leaves audit trail
  • 12. Global Auditor string audit; ! int logIn(string passwd){ audit += passwd; return 42; } ! double withdraw(int key){ audit += “withdrawing ”; return 100.0; } • Poor scaling, maintenance, flexibility
  • 13. In/Out Auditor pair<int, string> logIn(string passwd, string audit){ return make_pair(42, audit + passwd); } ! pair<double, string> withdraw(int key, string audit){ return make_pair(100.0 , audit + “withdrawing ”); } • Doesn’t memoize well • Each function has access to full log and must know how to accumulate data
  • 14. Out Auditor pair<int, string> logIn(string passwd){ return make_pair(42, passwd); } ! pair<double, string> withdraw(int key){ return make_pair(100.0 ,“withdrawing ”); } • Each function responsible only for its data • But how to compose such functions?
  • 15. Writer template<class A> using Writer = pair<A, string>; Writer<int> logIn(string passwd){ return make_pair(42, passwd); } ! Writer<double> withdraw(int key){ return make_pair(100.0 ,“withdrawing ”); } • How to compose?
  • 16. Composition Writer<double> transact(string passwd){ auto p1 logIn(passwd); auto p2 withdraw(p1.first); return make_pair(p2.first , p1.second + p2.second); } • Audit trail accumulated “between” calls
  • 17. Abstracting Composition template<class A, class B, class C> function<Writer<C>(A)> compose(function<Writer<B>(A)> f ,function<Writer<C>(B)> g) { return [f, g](A x) { auto p1 = f(x); auto p2 = g(p1.first); return make_pair(p2.first , p1.second + p2.second); }; } • Composing two functions using a higher order function
  • 18. Using Composition Writer<double> transact(string passwd){ return compose<string, int, double> (logIn, withdraw)(passwd); } • Between calls • Explicit type annotations
  • 19. Type Inference auto const compose = [](auto f, auto g) { return [f, g](auto x) { auto p1 = f(x); auto p2 = g(p1.first); return make_pair(p2.first , p1.second + p2.second); }; }; • C++14 generalized lambdas with return type deduction
  • 20. Objects, Arrows, Composition • Objects: Data Types • Arrows: (Pure) Functions • Composition: result of one function = argument of another function C g_after_f(A x) { B y = f(x); return g(y); }
  • 21. Category of Embellished Functions • Objects = types like A, B, C • Arrow from A to B = function from A to some type that depends on B (Embellished type) • For instance: pair<A, string> (or Writer<A>) • Composition: • f :: A → pair<B, string> • g :: B → pair<C, string> • g ∘ f :: A → pair<C, string>
  • 22. Kleisli Category template<class A> Writer<A> identity(A x) { return make_pair(x, ""); } auto const compose = [](auto f, auto g) { return [f, g](auto x) { auto p1 = f(x); auto p2 = g(p1.first); return make_pair(p2.first , p1.second + p2.second); }; };
  • 23. Controlling Side Effects • Pure functions • Side effects through composition • Write your code using embellished functions • Glue it using composition combinators
  • 24. Does it Generalize? • Writer generalizes to any monoid • Embellishment = Categorical Functor • Composition and identity for embellished functions = monad
  • 25. The Future Monad • Embellished functions: functions returning future<T> • Composition through then • Identity: make_ready_future
  • 26. Resumable Functions int cnt = 0; do { cnt = await streamR.read(512, buf); if ( cnt == 0 ) break; cnt = await streamW.write(cnt, buf); } while (cnt > 0); • Low level thinking: Coroutines, State • High level: Hiding the glue
  • 27. Resumable Generators generator<int> fib() { int a = 0; int b = 1; for (;;) { __yield_value a; auto next = a + b; a = b; b = next; } } • The same monadic pattern
  • 28. The C++ Opportunity • Grand Unification (Controlling side effects) • Futures • Ranges • Exceptions • Continuations • User-defined monads