SlideShare une entreprise Scribd logo
1  sur  29
Télécharger pour lire hors ligne
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…

Contenu connexe

Tendances

서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015
서버 개발자가 바라 본 Functional Reactive Programming with RxJava - SpringCamp2015NAVER / MusicPlatform
 
Introduction to functional programming using Ocaml
Introduction to functional programming using OcamlIntroduction to functional programming using Ocaml
Introduction to functional programming using Ocamlpramode_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 & howlucenerevolution
 
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
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!mickey24
 
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 RyuJITEgor Bogatov
 
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
 

Tendances (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
 

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

Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional ProgrammingFrancesco Bruni
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringSri 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 SwiftSaugat 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
 
Towards typesafe deep learning in scala
Towards typesafe deep learning in scalaTowards typesafe deep learning in scala
Towards typesafe deep learning in scalaTongfei Chen
 
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
 
Functional Programming, simplified
Functional Programming, simplifiedFunctional Programming, simplified
Functional Programming, simplifiedNaveenkumar Muguda
 
Iterarators and generators in python
Iterarators and generators in pythonIterarators and generators in python
Iterarators and generators in pythonSarfaraz 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 weekyoavrubin
 

Similaire à 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
 

Plus de 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
 

Plus de 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++ тонкости и нюансы
 
Аскетичная разработка браузера
Аскетичная разработка браузераАскетичная разработка браузера
Аскетичная разработка браузера
 

Dernier

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 

Dernier (20)

Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 

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…