SlideShare a Scribd company logo
Functional Programming in C++
and concurrent calculations
graninas@gmail.comAlexander Granin
Plan
● Functional Programming in C++
● Concurrent models
● Software Transactional Memory
● Monadic STM in C++
● Advanced Functional Programming in C++
Functional Programming in C++
Bartosz Milewski
Eric Niebler
Ivan Čukić
John Carmack
template<template<typename> class Monad>
auto run()
{
return
DO(Monad,
(x, unit(1))
(y, unit(2))
(z, DO(Monad,
(x, unit(5))
(_, unit(x - 2))
))
(_, unit(x + y + z))
);
}
Introduction to FP in C++: Monads!
Evgeny Panasyuk
https://github.com/evgeny-panasyuk/monad_do
Concurrent models
shared
resource
actor actor
std::shared_ptr std::shared_ptrint refCounter;
struct Chest
{
int iron;
int copper;
int coal;
};
iron (1)
copper (1)
copper (1)
iron (1)
coal (1)
struct Chest
{
std::atomic<int> iron;
std::atomic<int> copper;
std::atomic<int> coal;
};
iron (1)
copper (1)
copper (1)
iron (1)
coal (1)
struct Chest
{
std::atomic<int> iron;
std::atomic<int> copper;
std::atomic<int> coal;
};
iron < 100
copper < 100
coal > 6 && iron > 3
coal > 6 && copper > 3
iron (1)
copper (1)
coal (3), copper (3)
coal (3), iron (3)
coal (1)
coal < 100
struct Chest
{
int iron;
int copper;
int coal;
std::mutex lock;
};
iron < 100
copper < 100
coal > 6 && iron > 3
coal > 6 && copper > 3
iron (1)
copper (1)
coal (3), copper (3)
coal (3), iron (3)
coal (1)
coal < 100
Software Transactional Memory
Wyatt-STM
https://github.com/bretthall/Wyatt-STM
CppCon 2015: Brett Hall “Transactional Memory in Practice"
cpp_stm_free
https://github.com/graninas/cpp_stm_free
C++ Russia 2018 (Spb): “Functional approach to STM”
Transactions
struct Chest
{
stm::TVar<int> iron;
stm::TVar<int> copper;
stm::TVar<int> coal;
};
struct Chest
{
stm::TVar<int> iron;
stm::TVar<int> copper;
stm::TVar<int> coal;
};
STM-based concurrency
stm::STML<stm::Unit> insert(stm::TVar<int> resource, int count);
stm::STML<stm::Unit> extract( stm::TVar<int> resource1, int count1,
stm::TVar<int> resource2, int count2 );
struct Chest
{
stm::TVar<int> iron;
stm::TVar<int> copper;
stm::TVar<int> coal;
};
STM-based concurrency
stm::STML<stm::Unit> insert(stm::TVar<int> resource, int count);
stm::STML<stm::Unit> extract( stm::TVar<int> resource1, int count1,
stm::TVar<int> resource2, int count2 );
stm::Context ctx;
stm::atomically(ctx, insert(chest.iron, 1) ); // Thread 1
stm::atomically(ctx, insert(chest.copper, 1) ); // Thread 2
stm::atomically(ctx, insert(chest.coal, 1) ); // Thread 3
stm::atomically(ctx, extract(chest.coal, 3, chest.iron, 3) ); // Thread 4
stm::atomically(ctx, extract(chest.coal, 3, chest.copper, 3) ); // Thread 5
struct Chest
{
stm::TVar<int> iron;
stm::TVar<int> copper;
stm::TVar<int> coal;
};
STM-based concurrency
Monadic STM in C++
template <typename A>
STML<TVar<A>> newTVar(const A& val);
STM: TVar operations
newTVar :: a → STML (TVar a)
template <typename A>
STML<TVar<A>> newTVar(const A& val);
template <typename A>
STML<A> readTVar(const TVar<A>& tvar);
STM: TVar operations
newTVar :: a → STML (TVar a)
readTVar :: TVar a → STML a
template <typename A>
STML<TVar<A>> newTVar(const A& val);
template <typename A>
STML<A> readTVar(const TVar<A>& tvar);
template <typename A>
STML<Unit> writeTVar(const TVar<A>& tvar,
const A& val);
STM: TVar operations
newTVar :: a → STML (TVar a)
readTVar :: TVar a → STML a
writeTVar :: TVar a → a → STML ()
STM: Monadically composable transactions
transaction :: STML Int
transaction = do
tvar ← newTVar 10
readTVar tvar
STML<int> transaction() {
STML<TVar<int>> tvarTrans = newTVar(10);
// return readTVar(tvarTrans);
// ????
}
STM: Monadically composable transactions
transaction :: STML Int
transaction = do
tvar ← newTVar 10
readTVar tvar
transaction :: STML Int
transaction =
bind (newTVar 10) (tvar → readTVar tvar)
STML<int> transaction() {
STML<TVar<int>> tvarTrans = newTVar(10);
// return readTVar(tvarTrans);
// ????
}
STML<int> transaction() {
STML<TVar<int>> tvarTrans = newTVar(10);
return bind(tvarTrans,
[](TVar<int> tvar) {
return readTVar(tvar);
});
}
Sample: Extract resources transaction
STML<Unit> extract (TVar<int> resource1, int count1, TVar<int> resource2, int count2) {
STML<Unit> t1 = extractResource (resource1, count1);
STML<Unit> t2 = extractResource (resource2, count2);
return bind (t1, [=](Unit) { return t2; });
}
STML<Unit> extractResource (TVar<int> resource, int count) {
STML<int> trans1 = readTVar (resource);
return bind (trans1, [=](int value) {
return value >= count
? writeTVar (recource, value - count)
: retry();
});
}
STM: C++ Interface
template <typename A, typename B>
STML<B> bind(const STML<A> ma,
const std::function<STML<B>(A)>& f);
template <typename A>
STML<A> pure(const A& val);
template <typename A>
STML<A> retry();
template <typename A>
STML<TVar<A>> newTVar(const A& val);
template <typename A>
STML<A> readTVar(const TVar<A>& tvar);
template <typename A>
STML<Unit> writeTVar(const TVar<A>& tvar,
const A& val);
Advanced Functional Programming in C++
Design Pattern: eDSL
Language ScenarioComposition
Environment 1
Environment 2
...
Interpreting
(Evaluation)
template <typename A, typename Ret>
struct NewTVar
{
A val;
std::function<Ret(TVar<A>)> next;
};
template <typename A, typename Ret>
struct ReadTVar
{
TVar<A> tvar;
std::function<Ret(A)> next;
};
template <typename A, typename Ret>
struct WriteTVar
{
TVar<A> tvar;
A val;
std::function<Ret(fp::Unit)> next;
};
template <typename A, typename Ret>
struct Retry
{
};
STM eDSL
template <class Ret>
struct STMF
{
std::variant<NewTVar <std::any, Ret>,
ReadTVar <std::any, Ret>,
WriteTVar <std::any, Ret>,
Retry <std::any, Ret>
> stmf;
};
STM eDSL Generalized ADT
data STMF next where
NewTVar :: a -> (TVar a -> next) -> STMF next
WriteTVar :: TVar a -> a -> next -> STMF next
ReadTVar :: TVar a -> (a -> next) -> STMF next
Retry :: STMF next
template <typename A, typename B>
struct StmfFunctorVisitor
{
STMF<B> result;
void operator() (const NewTVar<std::any, STML<A>>& method);
void operator() (const ReadTVar<std::any, STML<A>>& method);
void operator() (const WriteTVar<std::any, STML<A>>& method);
void operator() (const Retry <std::any, STML<A>>&);
};
template <typename A, typename B>
STMF<B> fmap(const std::function<B(A)>& f, const STMF<A>& method) {
StmfFunctorVisitor<A, B> visitor(f);
std::visit(visitor, method.stmf);
return visitor.result;
}
STM eDSL ADT interpreting (“Pattern Matching”)
Monadic STML chains
transaction :: STML Int
transaction = do
tvar ← newTVar 42
v1 ← readTVar tvar
v2 ← pure 10
pure (v1 + v2)
STML<int> transaction()
{
return bind (newTVar (42), [=](TVar<int> tvar)
{
return bind (readTVar (tvar), [=](int v1)
{
return bind (pure (10), [=](int v2)
{
return pure (v1 + v2);
});
});
});
}
STML<int>
↳ STML<TVar<int>>
↳ STML<int>
↳ STML<int>
↳ STML<int>
Recursive STML type
STML<int> transaction()
{
return bind (newTVar (42), [=](TVar<int> tvar)
{
return bind (readTVar (tvar), [=](int v1)
{
return bind (pure (10), [=](int v2)
{
return pure (v1 + v2);
});
});
});
}
STML<int>
[](){}
↳ STML<TVar<int>>
[](){}
↳ STML<int>
[](){}
↳ STML<int>
[](){}
↳ STML<int>
Recursive STML type (lambda-enclosed)
STML<int> transaction()
{
return bind (newTVar (42), [=](TVar<int> tvar)
{
return bind (readTVar (tvar), [=](int v1)
{
return bind (pure (10), [=](int v2)
{
return pure (v1 + v2);
});
});
});
}
Free Monads
Free monad STM
NewTVar
WriteTVar
ReadTVar Retry
bind, pure STML<A>
“transaction”
Free ScenarioFree monad composition
STM eDSL (ADT)
Free monad (ADT)
Interpreting
Conflicts
Resolving Commit or Retry
Free monads
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
Binding complexity: O(n2
)
<stm/free/stm.h>
Free monads
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
-- Free monad, Church-encoded form
data ChurchFree f a
= ChurchFree { runChurch :: forall z. (a -> z)
-> (f z -> z)
-> z }
Binding complexity: O(n2
)
<stm/free/stm.h>
Binding complexity: O(n)
<stm/church/stm.h>
(10x faster)
Free monads
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
-- Free monad, Church-encoded form
data ChurchFree f a
= ChurchFree { runChurch :: forall z. (a -> z)
-> (f z -> z)
-> z }
-- Free monad, Scott-encoded form
data Free a = Free { runFree :: forall u . (a -> u)
-> (f (Free f a) -> u)
-> u }
Binding complexity: O(n2
)
<stm/free/stm.h>
Binding complexity: O(n)
<stm/church/stm.h>
(10x faster)
Binding complexity: O(n2
)
STML Free monad type (normal form)
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
-- STML Free monad type
type STML a = Free STMF a
STML Free monad type (normal form)
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
-- STML Free monad type
type STML a = Free STMF a
f ~ STMF
f (Free f a) ~ STMF (Free STMF a)
f (Free f a) ~ STMF (STML a)
STML Free monad type (normal form)
-- Free monad, normal form
data Free f a = Pure a
| Bind (f (Free f a))
-- STML Free monad type
type STML a = Free STMF a
f ~ STMF
f (Free f a) ~ STMF (Free STMF a)
f (Free f a) ~ STMF (STML a)
template <typename Ret>
struct STML {
std::variant<PureF<Ret>, BindF<Ret>> stml;
};
template <typename Ret>
struct PureF {
Ret ret;
};
template <typename Ret>
struct BindF {
STMF<STML<Ret>> stmf;
};
STML Free monad type (normal form)
template <typename Ret>
struct STML {
std::variant<PureF<Ret>, BindF<Ret>> stml;
};
template <typename Ret>
struct PureF {
Ret ret;
};
template <typename Ret>
struct BindF {
STMF<STML<Ret>> stmf;
};
template <class Ret>
struct STMF {
std::variant<NewTVar <std::any, Ret>,
ReadTVar <std::any, Ret>,
WriteTVar <std::any, Ret>,
Retry <std::any, Ret>
> stmf;
};
template <typename A, typename Ret>
struct NewTVar {
A val;
std::function<Ret(TVar<A>)> next;
};
STML monadic binding
template <typename A, typename B>
struct BindStmlVisitor;
template <typename A, typename B>
struct BindStmfVisitor;
template <typename A, typename B>
STML<B> bind(const STML<A>& stml, const std::function<STML<B>(A)>& f)
{
BindStmlVisitor<A, B> visitor(f);
std::visit(visitor, stml.stml);
return visitor.result;
}
Thank you for
watching!
Alexander Granin
graninas@gmail.com

More Related Content

What's hot

The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181
Mahmoud Samir Fayed
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
kinan keshkeh
 
The Ring programming language version 1.5.4 book - Part 35 of 185
The Ring programming language version 1.5.4 book - Part 35 of 185The Ring programming language version 1.5.4 book - Part 35 of 185
The Ring programming language version 1.5.4 book - Part 35 of 185
Mahmoud Samir Fayed
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
Dr. Md. Shohel Sayeed
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
Russell Childs
 
The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196
Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181
Mahmoud Samir Fayed
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
Jan Wedekind
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
aleks-f
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
tdc-globalcode
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
tdc-globalcode
 
The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210
Mahmoud Samir Fayed
 
Aspect Mining for Large Systems
Aspect Mining for Large SystemsAspect Mining for Large Systems
Aspect Mining for Large Systems
Thomas Zimmermann
 
The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202
Mahmoud Samir Fayed
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
Doug Hawkins
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
Doug Hawkins
 
The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181
Mahmoud Samir Fayed
 

What's hot (20)

The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181The Ring programming language version 1.5.2 book - Part 34 of 181
The Ring programming language version 1.5.2 book - Part 34 of 181
 
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
The Ring programming language version 1.5.4 book - Part 35 of 185
The Ring programming language version 1.5.4 book - Part 35 of 185The Ring programming language version 1.5.4 book - Part 35 of 185
The Ring programming language version 1.5.4 book - Part 35 of 185
 
Computer Programming- Lecture 9
Computer Programming- Lecture 9Computer Programming- Lecture 9
Computer Programming- Lecture 9
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196The Ring programming language version 1.7 book - Part 83 of 196
The Ring programming language version 1.7 book - Part 83 of 196
 
The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181The Ring programming language version 1.5.2 book - Part 13 of 181
The Ring programming language version 1.5.2 book - Part 13 of 181
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013
 
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
TDC2016POA | Trilha .NET - C# como você nunca viu: conceitos avançados de pro...
 
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDBTDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
TDC2016POA | Trilha .NET - CQRS e ES na prática com RavenDB
 
The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210The Ring programming language version 1.9 book - Part 94 of 210
The Ring programming language version 1.9 book - Part 94 of 210
 
Aspect Mining for Large Systems
Aspect Mining for Large SystemsAspect Mining for Large Systems
Aspect Mining for Large Systems
 
The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202The Ring programming language version 1.8 book - Part 116 of 202
The Ring programming language version 1.8 book - Part 116 of 202
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
Ds 2 cycle
Ds 2 cycleDs 2 cycle
Ds 2 cycle
 
The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181
 
OpenMP
OpenMPOpenMP
OpenMP
 

Similar to Functional programming in C++ LambdaNsk

Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile Time
emBO_Conference
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
Alexander Granin
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
phil_nash
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
NelyJay
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
GlobalLogic Ukraine
 
Ray Tracing with ZIO
Ray Tracing with ZIORay Tracing with ZIO
Ray Tracing with ZIO
Pierangelo Cecchetto
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
Simon Ritter
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
ssuser3cbb4c
 
Modern C++
Modern C++Modern C++
Modern C++
Michael Clark
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
Dr. Md. Shohel Sayeed
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
Võ Hòa
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210
Mahmoud Samir Fayed
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
sholavanalli
 
C++11
C++11C++11
C++11
C++11C++11

Similar to Functional programming in C++ LambdaNsk (20)

Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile Time
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approach
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methods
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
C++11 - STL Additions
C++11 - STL AdditionsC++11 - STL Additions
C++11 - STL Additions
 
Ray Tracing with ZIO
Ray Tracing with ZIORay Tracing with ZIO
Ray Tracing with ZIO
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
C++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptxC++ lectures all chapters in one slide.pptx
C++ lectures all chapters in one slide.pptx
 
Modern C++
Modern C++Modern C++
Modern C++
 
Computer Programming- Lecture 6
Computer Programming- Lecture 6Computer Programming- Lecture 6
Computer Programming- Lecture 6
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp full
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210The Ring programming language version 1.9 book - Part 30 of 210
The Ring programming language version 1.9 book - Part 30 of 210
 
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizationsEgor Bogatov - .NET Core intrinsics and other micro-optimizations
Egor Bogatov - .NET Core intrinsics and other micro-optimizations
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Oop objects_classes
Oop objects_classesOop objects_classes
Oop objects_classes
 
TechTalk - Dotnet
TechTalk - DotnetTechTalk - Dotnet
TechTalk - Dotnet
 
C++11
C++11C++11
C++11
 
C++11
C++11C++11
C++11
 

More from Alexander Granin

Concurrent applications with free monads and stm
Concurrent applications with free monads and stmConcurrent applications with free monads and stm
Concurrent applications with free monads and stm
Alexander Granin
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
Alexander Granin
 
Final tagless vs free monad
Final tagless vs free monadFinal tagless vs free monad
Final tagless vs free monad
Alexander Granin
 
Monadic parsers in C++
Monadic parsers in C++Monadic parsers in C++
Monadic parsers in C++
Alexander Granin
 
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
 
О разработке десктопных приложений / About desktop development
О разработке десктопных приложений / About desktop developmentО разработке десктопных приложений / About desktop development
О разработке десктопных приложений / About desktop development
Alexander Granin
 
Принципы и практики разработки ПО 2 / Principles and practices of software de...
Принципы и практики разработки ПО 2 / Principles and practices of software de...Принципы и практики разработки ПО 2 / Principles and practices of software de...
Принципы и практики разработки ПО 2 / Principles and practices of software de...
Alexander Granin
 
Принципы и практики разработки ПО / Principles and practices of software deve...
Принципы и практики разработки ПО / Principles and practices of software deve...Принципы и практики разработки ПО / Principles and practices of software deve...
Принципы и практики разработки ПО / Principles and practices of software deve...
Alexander Granin
 
Закон Деметры / Demetra's law
Закон Деметры / Demetra's lawЗакон Деметры / Demetra's law
Закон Деметры / Demetra's law
Alexander Granin
 
Design of big applications in FP
Design of big applications in FPDesign of big applications in FP
Design of big applications in FP
Alexander Granin
 
GitHub - зеркало разработчика
GitHub - зеркало разработчикаGitHub - зеркало разработчика
GitHub - зеркало разработчика
Alexander Granin
 
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
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentials
Alexander Granin
 
Вы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FPВы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FP
Alexander Granin
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonads
Alexander Granin
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
Alexander Granin
 
Дизайн больших приложений в ФП
Дизайн больших приложений в ФПДизайн больших приложений в ФП
Дизайн больших приложений в ФП
Alexander Granin
 
Линзы - комбинаторная манипуляция данными
Линзы - комбинаторная манипуляция даннымиЛинзы - комбинаторная манипуляция данными
Линзы - комбинаторная манипуляция данными
Alexander Granin
 
Линзы - комбинаторная манипуляция данными (Dev2Dev)
Линзы - комбинаторная манипуляция данными (Dev2Dev)Линзы - комбинаторная манипуляция данными (Dev2Dev)
Линзы - комбинаторная манипуляция данными (Dev2Dev)
Alexander Granin
 
Идиоматичный функциональный код
Идиоматичный функциональный кодИдиоматичный функциональный код
Идиоматичный функциональный код
Alexander Granin
 

More from Alexander Granin (20)

Concurrent applications with free monads and stm
Concurrent applications with free monads and stmConcurrent applications with free monads and stm
Concurrent applications with free monads and stm
 
Hierarchical free monads and software design in fp
Hierarchical free monads and software design in fpHierarchical free monads and software design in fp
Hierarchical free monads and software design in fp
 
Final tagless vs free monad
Final tagless vs free monadFinal tagless vs free monad
Final tagless vs free monad
 
Monadic parsers in C++
Monadic parsers in C++Monadic parsers in C++
Monadic parsers 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++
The present and the future of functional programming in c++
 
О разработке десктопных приложений / About desktop development
О разработке десктопных приложений / About desktop developmentО разработке десктопных приложений / About desktop development
О разработке десктопных приложений / About desktop development
 
Принципы и практики разработки ПО 2 / Principles and practices of software de...
Принципы и практики разработки ПО 2 / Principles and practices of software de...Принципы и практики разработки ПО 2 / Principles and practices of software de...
Принципы и практики разработки ПО 2 / Principles and practices of software de...
 
Принципы и практики разработки ПО / Principles and practices of software deve...
Принципы и практики разработки ПО / Principles and practices of software deve...Принципы и практики разработки ПО / Principles and practices of software deve...
Принципы и практики разработки ПО / Principles and practices of software deve...
 
Закон Деметры / Demetra's law
Закон Деметры / Demetra's lawЗакон Деметры / Demetra's law
Закон Деметры / Demetra's law
 
Design of big applications in FP
Design of big applications in FPDesign of big applications in FP
Design of big applications in FP
 
GitHub - зеркало разработчика
GitHub - зеркало разработчикаGitHub - зеркало разработчика
GitHub - зеркало разработчика
 
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++
 
Transition graph using free monads and existentials
Transition graph using free monads and existentialsTransition graph using free monads and existentials
Transition graph using free monads and existentials
 
Вы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FPВы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FP
 
Functional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonadsFunctional "Life": parallel cellular automata and comonads
Functional "Life": parallel cellular automata and comonads
 
Functional microscope - Lenses in C++
Functional microscope - Lenses in C++Functional microscope - Lenses in C++
Functional microscope - Lenses in C++
 
Дизайн больших приложений в ФП
Дизайн больших приложений в ФПДизайн больших приложений в ФП
Дизайн больших приложений в ФП
 
Линзы - комбинаторная манипуляция данными
Линзы - комбинаторная манипуляция даннымиЛинзы - комбинаторная манипуляция данными
Линзы - комбинаторная манипуляция данными
 
Линзы - комбинаторная манипуляция данными (Dev2Dev)
Линзы - комбинаторная манипуляция данными (Dev2Dev)Линзы - комбинаторная манипуляция данными (Dev2Dev)
Линзы - комбинаторная манипуляция данными (Dev2Dev)
 
Идиоматичный функциональный код
Идиоматичный функциональный кодИдиоматичный функциональный код
Идиоматичный функциональный код
 

Recently uploaded

Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
Deuglo Infosystem Pvt Ltd
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
Shane Coughlan
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
lorraineandreiamcidl
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
Google
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
Łukasz Chruściel
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
Aftab Hussain
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
TheSMSPoint
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
timtebeek1
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
Hironori Washizaki
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
kalichargn70th171
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
Hornet Dynamics
 

Recently uploaded (20)

Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Empowering Growth with Best Software Development Company in Noida - Deuglo
Empowering Growth with Best Software  Development Company in Noida - DeugloEmpowering Growth with Best Software  Development Company in Noida - Deuglo
Empowering Growth with Best Software Development Company in Noida - Deuglo
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
openEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain SecurityopenEuler Case Study - The Journey to Supply Chain Security
openEuler Case Study - The Journey to Supply Chain Security
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOMLORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
LORRAINE ANDREI_LEQUIGAN_HOW TO USE ZOOM
 
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI AppAI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
AI Fusion Buddy Review: Brand New, Groundbreaking Gemini-Powered AI App
 
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf2024 eCommerceDays Toulouse - Sylius 2.0.pdf
2024 eCommerceDays Toulouse - Sylius 2.0.pdf
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Graspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code AnalysisGraspan: A Big Data System for Big Code Analysis
Graspan: A Big Data System for Big Code Analysis
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Transform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR SolutionsTransform Your Communication with Cloud-Based IVR Solutions
Transform Your Communication with Cloud-Based IVR Solutions
 
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdfAutomated software refactoring with OpenRewrite and Generative AI.pptx.pdf
Automated software refactoring with OpenRewrite and Generative AI.pptx.pdf
 
SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024SWEBOK and Education at FUSE Okinawa 2024
SWEBOK and Education at FUSE Okinawa 2024
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
Why Mobile App Regression Testing is Critical for Sustained Success_ A Detail...
 
E-commerce Application Development Company.pdf
E-commerce Application Development Company.pdfE-commerce Application Development Company.pdf
E-commerce Application Development Company.pdf
 

Functional programming in C++ LambdaNsk

  • 1. Functional Programming in C++ and concurrent calculations graninas@gmail.comAlexander Granin
  • 2. Plan ● Functional Programming in C++ ● Concurrent models ● Software Transactional Memory ● Monadic STM in C++ ● Advanced Functional Programming in C++
  • 3. Functional Programming in C++ Bartosz Milewski Eric Niebler Ivan Čukić John Carmack
  • 4. template<template<typename> class Monad> auto run() { return DO(Monad, (x, unit(1)) (y, unit(2)) (z, DO(Monad, (x, unit(5)) (_, unit(x - 2)) )) (_, unit(x + y + z)) ); } Introduction to FP in C++: Monads! Evgeny Panasyuk https://github.com/evgeny-panasyuk/monad_do
  • 7.
  • 8.
  • 9.
  • 10. struct Chest { int iron; int copper; int coal; }; iron (1) copper (1) copper (1) iron (1) coal (1)
  • 11. struct Chest { std::atomic<int> iron; std::atomic<int> copper; std::atomic<int> coal; }; iron (1) copper (1) copper (1) iron (1) coal (1)
  • 12. struct Chest { std::atomic<int> iron; std::atomic<int> copper; std::atomic<int> coal; }; iron < 100 copper < 100 coal > 6 && iron > 3 coal > 6 && copper > 3 iron (1) copper (1) coal (3), copper (3) coal (3), iron (3) coal (1) coal < 100
  • 13. struct Chest { int iron; int copper; int coal; std::mutex lock; }; iron < 100 copper < 100 coal > 6 && iron > 3 coal > 6 && copper > 3 iron (1) copper (1) coal (3), copper (3) coal (3), iron (3) coal (1) coal < 100
  • 14.
  • 15. Software Transactional Memory Wyatt-STM https://github.com/bretthall/Wyatt-STM CppCon 2015: Brett Hall “Transactional Memory in Practice" cpp_stm_free https://github.com/graninas/cpp_stm_free C++ Russia 2018 (Spb): “Functional approach to STM”
  • 17. struct Chest { stm::TVar<int> iron; stm::TVar<int> copper; stm::TVar<int> coal; }; STM-based concurrency
  • 18. stm::STML<stm::Unit> insert(stm::TVar<int> resource, int count); stm::STML<stm::Unit> extract( stm::TVar<int> resource1, int count1, stm::TVar<int> resource2, int count2 ); struct Chest { stm::TVar<int> iron; stm::TVar<int> copper; stm::TVar<int> coal; }; STM-based concurrency
  • 19. stm::STML<stm::Unit> insert(stm::TVar<int> resource, int count); stm::STML<stm::Unit> extract( stm::TVar<int> resource1, int count1, stm::TVar<int> resource2, int count2 ); stm::Context ctx; stm::atomically(ctx, insert(chest.iron, 1) ); // Thread 1 stm::atomically(ctx, insert(chest.copper, 1) ); // Thread 2 stm::atomically(ctx, insert(chest.coal, 1) ); // Thread 3 stm::atomically(ctx, extract(chest.coal, 3, chest.iron, 3) ); // Thread 4 stm::atomically(ctx, extract(chest.coal, 3, chest.copper, 3) ); // Thread 5 struct Chest { stm::TVar<int> iron; stm::TVar<int> copper; stm::TVar<int> coal; }; STM-based concurrency
  • 21. template <typename A> STML<TVar<A>> newTVar(const A& val); STM: TVar operations newTVar :: a → STML (TVar a)
  • 22. template <typename A> STML<TVar<A>> newTVar(const A& val); template <typename A> STML<A> readTVar(const TVar<A>& tvar); STM: TVar operations newTVar :: a → STML (TVar a) readTVar :: TVar a → STML a
  • 23. template <typename A> STML<TVar<A>> newTVar(const A& val); template <typename A> STML<A> readTVar(const TVar<A>& tvar); template <typename A> STML<Unit> writeTVar(const TVar<A>& tvar, const A& val); STM: TVar operations newTVar :: a → STML (TVar a) readTVar :: TVar a → STML a writeTVar :: TVar a → a → STML ()
  • 24. STM: Monadically composable transactions transaction :: STML Int transaction = do tvar ← newTVar 10 readTVar tvar STML<int> transaction() { STML<TVar<int>> tvarTrans = newTVar(10); // return readTVar(tvarTrans); // ???? }
  • 25. STM: Monadically composable transactions transaction :: STML Int transaction = do tvar ← newTVar 10 readTVar tvar transaction :: STML Int transaction = bind (newTVar 10) (tvar → readTVar tvar) STML<int> transaction() { STML<TVar<int>> tvarTrans = newTVar(10); // return readTVar(tvarTrans); // ???? } STML<int> transaction() { STML<TVar<int>> tvarTrans = newTVar(10); return bind(tvarTrans, [](TVar<int> tvar) { return readTVar(tvar); }); }
  • 26. Sample: Extract resources transaction STML<Unit> extract (TVar<int> resource1, int count1, TVar<int> resource2, int count2) { STML<Unit> t1 = extractResource (resource1, count1); STML<Unit> t2 = extractResource (resource2, count2); return bind (t1, [=](Unit) { return t2; }); } STML<Unit> extractResource (TVar<int> resource, int count) { STML<int> trans1 = readTVar (resource); return bind (trans1, [=](int value) { return value >= count ? writeTVar (recource, value - count) : retry(); }); }
  • 27. STM: C++ Interface template <typename A, typename B> STML<B> bind(const STML<A> ma, const std::function<STML<B>(A)>& f); template <typename A> STML<A> pure(const A& val); template <typename A> STML<A> retry(); template <typename A> STML<TVar<A>> newTVar(const A& val); template <typename A> STML<A> readTVar(const TVar<A>& tvar); template <typename A> STML<Unit> writeTVar(const TVar<A>& tvar, const A& val);
  • 29. Design Pattern: eDSL Language ScenarioComposition Environment 1 Environment 2 ... Interpreting (Evaluation)
  • 30. template <typename A, typename Ret> struct NewTVar { A val; std::function<Ret(TVar<A>)> next; }; template <typename A, typename Ret> struct ReadTVar { TVar<A> tvar; std::function<Ret(A)> next; }; template <typename A, typename Ret> struct WriteTVar { TVar<A> tvar; A val; std::function<Ret(fp::Unit)> next; }; template <typename A, typename Ret> struct Retry { }; STM eDSL
  • 31. template <class Ret> struct STMF { std::variant<NewTVar <std::any, Ret>, ReadTVar <std::any, Ret>, WriteTVar <std::any, Ret>, Retry <std::any, Ret> > stmf; }; STM eDSL Generalized ADT data STMF next where NewTVar :: a -> (TVar a -> next) -> STMF next WriteTVar :: TVar a -> a -> next -> STMF next ReadTVar :: TVar a -> (a -> next) -> STMF next Retry :: STMF next
  • 32. template <typename A, typename B> struct StmfFunctorVisitor { STMF<B> result; void operator() (const NewTVar<std::any, STML<A>>& method); void operator() (const ReadTVar<std::any, STML<A>>& method); void operator() (const WriteTVar<std::any, STML<A>>& method); void operator() (const Retry <std::any, STML<A>>&); }; template <typename A, typename B> STMF<B> fmap(const std::function<B(A)>& f, const STMF<A>& method) { StmfFunctorVisitor<A, B> visitor(f); std::visit(visitor, method.stmf); return visitor.result; } STM eDSL ADT interpreting (“Pattern Matching”)
  • 33. Monadic STML chains transaction :: STML Int transaction = do tvar ← newTVar 42 v1 ← readTVar tvar v2 ← pure 10 pure (v1 + v2) STML<int> transaction() { return bind (newTVar (42), [=](TVar<int> tvar) { return bind (readTVar (tvar), [=](int v1) { return bind (pure (10), [=](int v2) { return pure (v1 + v2); }); }); }); }
  • 34. STML<int> ↳ STML<TVar<int>> ↳ STML<int> ↳ STML<int> ↳ STML<int> Recursive STML type STML<int> transaction() { return bind (newTVar (42), [=](TVar<int> tvar) { return bind (readTVar (tvar), [=](int v1) { return bind (pure (10), [=](int v2) { return pure (v1 + v2); }); }); }); }
  • 35. STML<int> [](){} ↳ STML<TVar<int>> [](){} ↳ STML<int> [](){} ↳ STML<int> [](){} ↳ STML<int> Recursive STML type (lambda-enclosed) STML<int> transaction() { return bind (newTVar (42), [=](TVar<int> tvar) { return bind (readTVar (tvar), [=](int v1) { return bind (pure (10), [=](int v2) { return pure (v1 + v2); }); }); }); }
  • 37. Free monad STM NewTVar WriteTVar ReadTVar Retry bind, pure STML<A> “transaction” Free ScenarioFree monad composition STM eDSL (ADT) Free monad (ADT) Interpreting Conflicts Resolving Commit or Retry
  • 38. Free monads -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) Binding complexity: O(n2 ) <stm/free/stm.h>
  • 39. Free monads -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) -- Free monad, Church-encoded form data ChurchFree f a = ChurchFree { runChurch :: forall z. (a -> z) -> (f z -> z) -> z } Binding complexity: O(n2 ) <stm/free/stm.h> Binding complexity: O(n) <stm/church/stm.h> (10x faster)
  • 40. Free monads -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) -- Free monad, Church-encoded form data ChurchFree f a = ChurchFree { runChurch :: forall z. (a -> z) -> (f z -> z) -> z } -- Free monad, Scott-encoded form data Free a = Free { runFree :: forall u . (a -> u) -> (f (Free f a) -> u) -> u } Binding complexity: O(n2 ) <stm/free/stm.h> Binding complexity: O(n) <stm/church/stm.h> (10x faster) Binding complexity: O(n2 )
  • 41. STML Free monad type (normal form) -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) -- STML Free monad type type STML a = Free STMF a
  • 42. STML Free monad type (normal form) -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) -- STML Free monad type type STML a = Free STMF a f ~ STMF f (Free f a) ~ STMF (Free STMF a) f (Free f a) ~ STMF (STML a)
  • 43. STML Free monad type (normal form) -- Free monad, normal form data Free f a = Pure a | Bind (f (Free f a)) -- STML Free monad type type STML a = Free STMF a f ~ STMF f (Free f a) ~ STMF (Free STMF a) f (Free f a) ~ STMF (STML a) template <typename Ret> struct STML { std::variant<PureF<Ret>, BindF<Ret>> stml; }; template <typename Ret> struct PureF { Ret ret; }; template <typename Ret> struct BindF { STMF<STML<Ret>> stmf; };
  • 44. STML Free monad type (normal form) template <typename Ret> struct STML { std::variant<PureF<Ret>, BindF<Ret>> stml; }; template <typename Ret> struct PureF { Ret ret; }; template <typename Ret> struct BindF { STMF<STML<Ret>> stmf; }; template <class Ret> struct STMF { std::variant<NewTVar <std::any, Ret>, ReadTVar <std::any, Ret>, WriteTVar <std::any, Ret>, Retry <std::any, Ret> > stmf; }; template <typename A, typename Ret> struct NewTVar { A val; std::function<Ret(TVar<A>)> next; };
  • 45. STML monadic binding template <typename A, typename B> struct BindStmlVisitor; template <typename A, typename B> struct BindStmfVisitor; template <typename A, typename B> STML<B> bind(const STML<A>& stml, const std::function<STML<B>(A)>& f) { BindStmlVisitor<A, B> visitor(f); std::visit(visitor, stml.stml); return visitor.result; }
  • 46. Thank you for watching! Alexander Granin graninas@gmail.com