SlideShare a Scribd company logo
Re-discovering 
Monads in C++ 
Bartosz Milewski, Бартош Милевски 
Twitter: @BartoszMilewski 
Novosibirsk, November 2014
Data in Boxes 
• Smart pointers: unique_ptr, shared_ptr 
• Optional, expected 
• Containers, ranges 
• Streams, channels (telemetry, stock quotes) 
• Futures 
• Database queries
In and Out of Boxes 
• Common patterns in data processing 
• Extract data from box 
• Process it 
• Put it back in a box 
for (int i = 0; i < len; ++i) 
w.push_back(f(v[i]));
Separate Concerns 
• Separate extraction/repacking from processing 
• Get rid of unessential variables 
• Iterators and algorithms: better but not much 
transform(begin(v), end(v), back_inserter(w), f);
Declarative Approach 
• Describe “what” rather than “how” 
• Example: ranges 
int total = accumulate(view::iota(1) | 
view::transform([](int x){return x*x;}) | 
view::take(10), 0);
Functor
Change of Perspective 
• Take a function that acts on items 
[](int x){return x*x;} 
• Lift it using view::transform 
view::transform([](int x){return x*x;}) 
• Lifted function acts on ranges of items {1, 2, 3, 4, …} 
view::iota(1) | 
view::transform([](int x){return x*x;}) 
• Returns a range of items {1, 4, 9, 16, …}
range 
1, 2, 3, 4 
range 
1, 4, 9, 16 
transform(square) 
transform 
x x*x 
square
Laziness 
• Infinite range {1, 2, 3, 4, …} 
std::iota(1) 
• Can’t process it eagerly! 
• Transform it lazily, on demand 
• Working with data that can’t fit in memory 
• infinite ranges 
• big data 
• database queries: LINQ
Functor Pattern 
• Function on types (type template) 
• Take any type T and produce Functor<T> 
• Function on functions 
• Take any function f from t1 to t2 
• Return a function from Functor<t1> to Functor<t2> 
• Preserve identity 
• Preserve composition
Range as Functor 
• Function on types: T to range<T> 
• Function on functions: view::transform 
view::iota(1) | 
view::transform([](int x){return x*x;}) | 
view::take(10)
future as Functor 
• A box that may eventually contain a value of type T 
std::future<T> fut = std::async(…); 
• Processing this value: 
auto x = fut.get(); // may block 
auto y = f(x); 
• Lifting a function using next: 
auto y = fut.next(f).get(); // proposed 
• fut.next(f).next(g).get();
Pointed Functor
Lifting Values 
• A pointed functor is a functor 
• Function on types 
• Function on functions (lifting functions) 
• Lifting a single value 
• A template function from T to Functor<T>
Examples 
• Containers: Creating a singleton container 
vector<double> {3.14} 
• Lazy range: view::single 
• Future: make_ready_future (proposed) 
• Usage: 
• return value when Functor expected 
• terminate recursion
Applicative Functor
Lifting Multi-Arg Functions 
• Applicative functor is a pointed functor: 
• Function on types 
• Lifting functions and values 
• Lifting multi-argument functions to functions taking 
multiple Functor arguments (of different types)
Lazy Applicative Range (1) 
• Example: Apply 2-arg function plus to two ranges 
zip_with(plus, r1, r2); 
• Variadic template zip_with 
• Takes a function f of n-arguments 
• Takes n ranges of corresponding types 
• Applies f to corresponding elements (until one of the 
ranges runs out) 
• Value lifting through repeat (infinite range)
Lazy Applicative Range (2) 
• Apply n-argument function to all combinations of 
values from n-ranges 
• Could be an overload of view::transform ? 
• Implemented as nested loop 
• Value lifting through single
Applicative Law 
• Lifting a 1-argument function 
• As function: transform(f, r) 
• As value (1): repeat(f) 
• Applying it to range: 
zip_with(apply, repeat(f), r) 
• As value (2): single(f) 
• Applying it to range: 
transform(apply, single(f), r)
Applicative future 
• Apply multi-argument function to multiple futures 
• Not planned, instead when_all 
• To apply the function, all arguments must be ready 
• Problem: futures may return exceptions, so it’s a 
combination of applicatives
Monad
Functor Factories 
• Library writer provides functions that return 
Functors 
• User wants to define their own 
• How do you chain Functor factories? 
Functor<t2> makeT2(t1); 
Functor<t3> makeT3(t2);
Future example 
• Composing asynchronous calls 
future<HANDLE> async_open(string &); 
future<Buffer> async_read(HANDLE fh); 
• Option 1: call get() twice 
• Option 2: call next. Problem: Double future. 
future<future<Buffer>> ffBuf = 
async_open(“foo").next(&async_read); 
• Solution: Collapse double future using unwrap() 
async_open("foo").next(&async_read).unwrap() 
.next(&async_process); 
• Better solution (proposed): Overload next for functions returning futures
Range Example 
• Functions returning ranges: Range factories 
• Applying range factory to range factory using 
transform results in a range of ranges 
• Collapsing using flatten 
• Combination of transform and flatten called 
for_each
Pythagorean Triples 
auto triples = 
for_each(ints(1), [](int z) { 
return for_each(ints(1, z), [=](int x) { 
return for_each(ints(x, z), [=](int y) { 
return yield_if(x*x + y*y == z*z, 
std::make_tuple(x, y, z)); 
}); 
}); 
}); 
• yield is the same as single inside for_each 
• yield_if is conditional yield (monad plus)
Monad 
• Monad is an applicative functor 
• function on types 
• function on functions: function lifting 
• value lifting 
• multi-argument function lifting 
• Flatten (reduce double Functor to single Functor) 
• Or Bind (combination of lifting and flatten) 
• And some monad laws
Current Problems 
• Lack of an overall abstraction (a monad template) 
• Random naming 
• fmap, transform, next, then, Select (LINQ) 
• pure, single, yield, await, make_ready_future 
• bind, for_each, next, then, SelectMany 
• Need syntactic sugar, like Haskell do notation 
• Resumable functions (proposed)
Conclusion 
• The same pattern fits many problems 
• ranges, lazy ranges 
• optional, expected 
• futures 
• LINQ (IEnumerable) 
• state, continuation, input, output 
• many more…

More Related Content

What's hot

Polymorphism
PolymorphismPolymorphism
Polymorphism
mohamed sikander
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
NAVER / MusicPlatform
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
pramode_ce
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
GeeksLab Odessa
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
lucenerevolution
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
규영 허
 
Java8 stream
Java8 streamJava8 stream
Java8 streamkoji lin
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
hhliu
 
C programs
C programsC programs
C programs
Vikram Nandini
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!mickey24
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
Dr. Md. Shohel Sayeed
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
Zsolt Mészárovics
 
Frsa
FrsaFrsa
Frsa
_111
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
Egor Bogatov
 
C++ references
C++ referencesC++ references
C++ references
corehard_by
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting StartedTeerawat Issariyakul
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
Russell Childs
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugsComputer Science Club
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
Dr. Md. Shohel Sayeed
 

What's hot (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocaml
 
V8
V8V8
V8
 
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
Java/Scala Lab: Анатолий Кметюк - Scala SubScript: Алгебра для реактивного пр...
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Chapter 7 functions (c)
Chapter 7 functions (c)Chapter 7 functions (c)
Chapter 7 functions (c)
 
C programs
C programsC programs
C programs
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
 
Lecture 12: Classes and Files
Lecture 12: Classes and FilesLecture 12: Classes and Files
Lecture 12: Classes and Files
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Frsa
FrsaFrsa
Frsa
 
How to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJITHow to add an optimization for C# to RyuJIT
How to add an optimization for C# to RyuJIT
 
C++ references
C++ referencesC++ references
C++ references
 
20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started20100712-OTcl Command -- Getting Started
20100712-OTcl Command -- Getting Started
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs20140531 serebryany lecture02_find_scary_cpp_bugs
20140531 serebryany lecture02_find_scary_cpp_bugs
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 

Similar to Bartosz Milewski, “Re-discovering Monads in C++”

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
Sri Harsha Pamu
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
Saugat Gautam
 
Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++
Satalia
 
C++ Language
C++ LanguageC++ Language
C++ Language
Syed Zaid Irshad
 
Functions
FunctionsFunctions
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scala
Tongfei Chen
 
Functions
FunctionsFunctions
Functions
Gaurav Subham
 
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++
Manzoor ALam
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
Naveenkumar Muguda
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
Sarfaraz Ghanta
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
Megha V
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
yoavrubin
 

Similar to Bartosz Milewski, “Re-discovering Monads in C++” (20)

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
Functions12
Functions12Functions12
Functions12
 
Functions123
Functions123 Functions123
Functions123
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
Functional Programming in Swift
Functional Programming in SwiftFunctional Programming in Swift
Functional Programming in Swift
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++Options and trade offs for parallelism and concurrency in Modern C++
Options and trade offs for parallelism and concurrency in Modern C++
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Functions
FunctionsFunctions
Functions
 
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scala
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Functions
FunctionsFunctions
Functions
 
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++
 
functions
functionsfunctions
functions
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplified
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in python
 
Python programming- Part IV(Functions)
Python programming- Part IV(Functions)Python programming- Part IV(Functions)
Python programming- Part IV(Functions)
 
Functional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks weekFunctional Programming in Javascript - IL Tech Talks week
Functional Programming in Javascript - IL Tech Talks week
 

More from Platonov Sergey

Евгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализацияЕвгений Зуев, С++ в России: Стандарт языка и его реализация
Евгений Зуев, С++ в России: Стандарт языка и его реализация
Platonov Sergey
 
Алексей Кутумов, C++ без исключений, часть 3
Алексей Кутумов,  C++ без исключений, часть 3Алексей Кутумов,  C++ без исключений, часть 3
Алексей Кутумов, C++ без исключений, часть 3
Platonov 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 на Linux
Platonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IIДмитрий Кашицын, Вывод типов в динамических и не очень языках II
Дмитрий Кашицын, Вывод типов в динамических и не очень языках II
Platonov Sergey
 
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках IДмитрий Кашицын, Вывод типов в динамических и не очень языках I
Дмитрий Кашицын, Вывод типов в динамических и не очень языках I
Platonov Sergey
 
QML\Qt Quick на практике
QML\Qt Quick на практикеQML\Qt Quick на практике
QML\Qt Quick на практике
Platonov Sergey
 
Визуализация автомобильных маршрутов
Визуализация автомобильных маршрутовВизуализация автомобильных маршрутов
Визуализация автомобильных маршрутов
Platonov Sergey
 
Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++Функциональный микроскоп: линзы в C++
Функциональный микроскоп: линзы в C++
Platonov Sergey
 
C++ exceptions
C++ exceptionsC++ exceptions
C++ exceptions
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-08
Platonov 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

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 

Bartosz Milewski, “Re-discovering Monads in C++”

  • 1. Re-discovering Monads in C++ Bartosz Milewski, Бартош Милевски Twitter: @BartoszMilewski Novosibirsk, November 2014
  • 2. Data in Boxes • Smart pointers: unique_ptr, shared_ptr • Optional, expected • Containers, ranges • Streams, channels (telemetry, stock quotes) • Futures • Database queries
  • 3. In and Out of Boxes • Common patterns in data processing • Extract data from box • Process it • Put it back in a box for (int i = 0; i < len; ++i) w.push_back(f(v[i]));
  • 4. Separate Concerns • Separate extraction/repacking from processing • Get rid of unessential variables • Iterators and algorithms: better but not much transform(begin(v), end(v), back_inserter(w), f);
  • 5. Declarative Approach • Describe “what” rather than “how” • Example: ranges int total = accumulate(view::iota(1) | view::transform([](int x){return x*x;}) | view::take(10), 0);
  • 7. Change of Perspective • Take a function that acts on items [](int x){return x*x;} • Lift it using view::transform view::transform([](int x){return x*x;}) • Lifted function acts on ranges of items {1, 2, 3, 4, …} view::iota(1) | view::transform([](int x){return x*x;}) • Returns a range of items {1, 4, 9, 16, …}
  • 8. range 1, 2, 3, 4 range 1, 4, 9, 16 transform(square) transform x x*x square
  • 9. Laziness • Infinite range {1, 2, 3, 4, …} std::iota(1) • Can’t process it eagerly! • Transform it lazily, on demand • Working with data that can’t fit in memory • infinite ranges • big data • database queries: LINQ
  • 10. Functor Pattern • Function on types (type template) • Take any type T and produce Functor<T> • Function on functions • Take any function f from t1 to t2 • Return a function from Functor<t1> to Functor<t2> • Preserve identity • Preserve composition
  • 11. Range as Functor • Function on types: T to range<T> • Function on functions: view::transform view::iota(1) | view::transform([](int x){return x*x;}) | view::take(10)
  • 12. future as Functor • A box that may eventually contain a value of type T std::future<T> fut = std::async(…); • Processing this value: auto x = fut.get(); // may block auto y = f(x); • Lifting a function using next: auto y = fut.next(f).get(); // proposed • fut.next(f).next(g).get();
  • 14. Lifting Values • A pointed functor is a functor • Function on types • Function on functions (lifting functions) • Lifting a single value • A template function from T to Functor<T>
  • 15. Examples • Containers: Creating a singleton container vector<double> {3.14} • Lazy range: view::single • Future: make_ready_future (proposed) • Usage: • return value when Functor expected • terminate recursion
  • 17. Lifting Multi-Arg Functions • Applicative functor is a pointed functor: • Function on types • Lifting functions and values • Lifting multi-argument functions to functions taking multiple Functor arguments (of different types)
  • 18. Lazy Applicative Range (1) • Example: Apply 2-arg function plus to two ranges zip_with(plus, r1, r2); • Variadic template zip_with • Takes a function f of n-arguments • Takes n ranges of corresponding types • Applies f to corresponding elements (until one of the ranges runs out) • Value lifting through repeat (infinite range)
  • 19. Lazy Applicative Range (2) • Apply n-argument function to all combinations of values from n-ranges • Could be an overload of view::transform ? • Implemented as nested loop • Value lifting through single
  • 20. Applicative Law • Lifting a 1-argument function • As function: transform(f, r) • As value (1): repeat(f) • Applying it to range: zip_with(apply, repeat(f), r) • As value (2): single(f) • Applying it to range: transform(apply, single(f), r)
  • 21. Applicative future • Apply multi-argument function to multiple futures • Not planned, instead when_all • To apply the function, all arguments must be ready • Problem: futures may return exceptions, so it’s a combination of applicatives
  • 22. Monad
  • 23. Functor Factories • Library writer provides functions that return Functors • User wants to define their own • How do you chain Functor factories? Functor<t2> makeT2(t1); Functor<t3> makeT3(t2);
  • 24. Future example • Composing asynchronous calls future<HANDLE> async_open(string &); future<Buffer> async_read(HANDLE fh); • Option 1: call get() twice • Option 2: call next. Problem: Double future. future<future<Buffer>> ffBuf = async_open(“foo").next(&async_read); • Solution: Collapse double future using unwrap() async_open("foo").next(&async_read).unwrap() .next(&async_process); • Better solution (proposed): Overload next for functions returning futures
  • 25. Range Example • Functions returning ranges: Range factories • Applying range factory to range factory using transform results in a range of ranges • Collapsing using flatten • Combination of transform and flatten called for_each
  • 26. Pythagorean Triples auto triples = for_each(ints(1), [](int z) { return for_each(ints(1, z), [=](int x) { return for_each(ints(x, z), [=](int y) { return yield_if(x*x + y*y == z*z, std::make_tuple(x, y, z)); }); }); }); • yield is the same as single inside for_each • yield_if is conditional yield (monad plus)
  • 27. Monad • Monad is an applicative functor • function on types • function on functions: function lifting • value lifting • multi-argument function lifting • Flatten (reduce double Functor to single Functor) • Or Bind (combination of lifting and flatten) • And some monad laws
  • 28. Current Problems • Lack of an overall abstraction (a monad template) • Random naming • fmap, transform, next, then, Select (LINQ) • pure, single, yield, await, make_ready_future • bind, for_each, next, then, SelectMany • Need syntactic sugar, like Haskell do notation • Resumable functions (proposed)
  • 29. Conclusion • The same pattern fits many problems • ranges, lazy ranges • optional, expected • futures • LINQ (IEnumerable) • state, continuation, input, output • many more…