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

Contenu connexe

Tendances

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 181Mahmoud 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 overloadingkinan 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 185Mahmoud Samir Fayed
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
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 196Mahmoud 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 181Mahmoud 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 2009Jan Wedekind
 
Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013Dynamic C++ ACCU 2013
Dynamic C++ ACCU 2013aleks-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 RavenDBtdc-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 210Mahmoud Samir Fayed
 
Aspect Mining for Large Systems
Aspect Mining for Large SystemsAspect Mining for Large Systems
Aspect Mining for Large SystemsThomas 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 202Mahmoud Samir Fayed
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug 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 181Mahmoud Samir Fayed
 

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

Similaire à Functional programming in C++ LambdaNsk

Programming at Compile Time
Programming at Compile TimeProgramming at Compile Time
Programming at Compile TimeemBO_Conference
 
Software transactional memory. pure functional approach
Software transactional memory. pure functional approachSoftware transactional memory. pure functional approach
Software transactional memory. pure functional approachAlexander Granin
 
C++ extension methods
C++ extension methodsC++ extension methods
C++ extension methodsphil_nash
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon 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.pptxssuser3cbb4c
 
Getting started cpp full
Getting started cpp   fullGetting started cpp   full
Getting started cpp fullVõ 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 210Mahmoud 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-optimizationsEgor Bogatov
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 

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

Plus de 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 stmAlexander 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 fpAlexander Granin
 
Final tagless vs free monad
Final tagless vs free monadFinal tagless vs free monad
Final tagless vs free monadAlexander 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 developmentAlexander 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 lawAlexander Granin
 
Design of big applications in FP
Design of big applications in FPDesign of big applications in FP
Design of big applications in FPAlexander 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 existentialsAlexander Granin
 
Вы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FPВы не понимаете ФП / You don't understand FP
Вы не понимаете ФП / You don't understand FPAlexander 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 comonadsAlexander 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
 

Plus de 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)
 
Идиоматичный функциональный код
Идиоматичный функциональный кодИдиоматичный функциональный код
Идиоматичный функциональный код
 

Dernier

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Dernier (20)

5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

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