SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
Cat’s anatomy
...overview of a functional library for C++14
Nicola Bonelli <nicola@pfq.io>
www.italiancpp.org
Overview
What is cat?
● Cat is a C++14 functional library inspired by Haskell
● It consists of 97 headers roughly divided into 3 major
groups
○ Utilities for the functional programmer
○ Common type-classes
○ Instances of type classes (instances of standard C++ types)
● Is the library mature?
○ No, it is still a work in progress
○ Documentation is still missing… :(
To whom is it useful?
● C++ coders that need some utility functions
○ Cat fills the gap of C++ libraries with respect to functional programming,
perfect forwarding, tuple manipulation, type traits, etc...
● C++ coders that want to move their first steps toward
functional programming
○ if you master functional thinking the pain to switch to Haskell will be relieved
○ conversely, porting projects from Haskell to C++ become much more simple
● Functional thinking improves the quality of C++ code!
Library tree
├── cat
│ ├── applicative/...
│ ├── applicative.hpp
│ ├── bifunctor/...
│ ├── bifunctor.hpp
│ ├── bits/...
│ ├── __config.hpp
│ ├── container.hpp
│ ├── foldable/...
│ ├── foldable.hpp
│ ├── functional.hpp
│ ├── functor/...
│ ├── functor.hpp
│ ├── infix.hpp
│ ├── iterator.hpp
│ ├── match.hpp
│ ├── meta.hpp
│ ├── monad/...
│ ├── monad.hpp
│ ├── monoid/...
│ ├── monoid.hpp
│ ├── optional.hpp
│ ├── placeholders.hpp
│ ├── read/...
│ ├── read.hpp
│ ├── section.hpp
│ ├── show/...
│ ├── show.hpp
│ ├── string_view.hpp
│ ├── tuple.hpp
│ ├── type_traits.hpp
│ └── utility.hpp
├── example/...
│ └── parser/...
└── test/...
├── CMakeLists.txt
├── inc/...
├── test/...
Utility functions
Category Functions
functional utilities curry, curry_as, compose (^), flip, on...
container fold operations, etc.
infix, sections, match utility for infix operators, sections
(binary operators), pattern matching...
type traits function_type, function_arity,
return_type, arg_type_at...
perfect forwarding const_forward, forward_as,
forward_iterator...
tuple make_typle, tuple_assign, tuple_foreach,
tuple_map, tuple_apply...
Type classes and instances
Type-class Instances
functor vector, deque, list, forward_list,
string, map, multimap, (unordered_*),
optional, pair, shared_ptr, unique_ptr,
future...
bifunctor pair
applicative, alternative vector, deque, list, forward_list,
optional, pair, shared_ptr, unique_ptr,
future...
foldable vector, deque, list, forward_list,
string, map, multimap, set, multiset,
(unordered_*), optional, pair,
shared_ptr, unique_ptr...
Type classes and instances
Type-class Instances
monoid vector, deque, list, forward_list,
string, map, multimap, set, multiset,
(unordered_*), optional, pair,
shared_ptr, unique_ptr, future...
monad, monad plus vector, deque, list, forward_list,
string, optional, shared_ptr, unique_ptr,
future...
read, show containers, chrono, fundamentals,
optional, string types, tuples
A functional approach...
In functional programming (FP)...
● Function is a first-class citizen
○ it can be passed to or returned from functions
● Functions are composable and support partial
application
○ improve code reusability
● Pure functions
○ have no observable side effects
○ referential transparency
● Data immutability
○ concurrent programming
Functions and arguments in C++?
● PF encourages a C++ callable type that
○ is pure (does not evaluate on the basis of a global states)
○ does not change the arguments passed
● A pure function can takes arguments by:
○ value
○ const L-value reference
○ R-value reference
○ universal reference (T &&)
● What’s the recommended method?
Argument passing comparisons
semantic retain ownership pros cons
value ● copyable? yes
● non-copyable ? no
(need move)
● clean design
● good for sink fun.
● 1 function to
maintain
● non copyable object needs to
be moved
● non-cheap copyable object is
inefficient
const L-value ref. ● yes ● ideal interface
● no extra copy/move
● 2^n overloads
R-value ref. ● no, but desidered ● good perf. ● 2^n overloads
universal ref (T &&)
note: (std::vector<T> &&) is not a
forwarding reference...
● yes ● no extra copy/move
● 1 function to
maintain
● enforce the const L-value ref.
● the argument must be a template
● wrong types passed generate
template error hell.
Argument passing with perfect forwarding
● Allows to pass both L-value and R-value arguments
● No extra copy or extra move is required
● Allows to retain the ownership of passed objects
○ non-copyable objects does not have to be moved (as req. in pass-by-
value)
● If R-value expression is passed then the function can
take advantage of it
○ moving elements out of an expiring container
Cat general design
● Cat takes advantage of
○ Extensibility
■ instances of a given type are implemented as partial specializations of certain C++
classes
○ Static polymorphism
■ Cat exploits C++ inheritance only to ensure that interfaces are complete (default
implementations are possible)
○ Non being OOP
■ free functions (or constexpr callables types)
○ Modern C++
■ constexpr constructors for building objects at compile time
■ override/final help compiler deals with C++ methods (devirtualization)
■ auto for trailing return type deduction
Utility functions
Perfect forwarding
● Universal reference allows to perfect forward
expressions from generic functions
○ T && arg
■ T && looks like a R-value ref. (but it is not)
■ yet, arg is an L-value expression.
○ std::forward is used to restore the original type:
■ std::forward<T>(arg)
● T can either be Object& or Object
● Reduce the number of functions to maintain:
○ for each argument one should maintain two versions
■ Object &&arg, and Object const &arg
■ (2^n with the number of arguments)
○ T && can also be used in variadic functions: Ts && ...args
Perfect forwarding
template <typename F, typename T>
auto map(F fun, std::vector<T> const & xs)
{ …
for(auto & x : xs)
… = fun(x);
template <typename F, typename T>
auto map(F fun, std::vector<T> && xs)
{ …
for(auto & x : xs)
… = fun(std::move(x));
Perfect forwarding
template <typename F, typename T>
auto map(F fun, std::vector<T> const & xs)
{ …
for(auto & x : xs)
… = fun(x);
template <typename F, typename T>
auto map(F fun, std::vector<T> && xs)
{ …
for(auto & x : xs)
… = fun(std::move(x));
template <typename F, typename Vector>
auto map(F fun, Vector && xs)
{ …
for(auto & x : xs)
… = fun(???(x));
how to forward this?
Perfect forwarding
template <typename F, typename T>
auto map(F fun, std::vector<T> const & xs)
{ …
for(auto & x : xs)
… = fun(x);
template <typename F, typename T>
auto map(F fun, std::vector<T> && xs)
{ …
for(auto & x : xs)
… = fun(std::move(x));
template <typename F, typename Vector>
auto map(F fun, Vector && xs)
{ …
for(auto & x : xs)
… = fun(cat::forward_as<Vector>(x));
forward_as
● Forward_as implementation:
template<typename T, typename V>
decltype(auto)
forward_as(V && value)
{
return static_cast<
std::conditional_t<
std::is_lvalue_reference<T>::value,
std::remove_reference_t<V> &,
std::remove_reference_t<V> &&>>(value);
}
iterator or move_iterator?
● Homework
○ “...write a function that takes two vectors and returns a new one, the
result of concatenation.”
● Elements contained could be:
○ cheap to move and expensive to copy
● Suggestion:
○ take into account the L/R value-ness of the vectors passed...
iterator or move_iterator?
template <typename T>
auto concat(std::vector<T> const &xs, std::vector<T> const &ys)
{
auto ret = xs;
ret.insert(std::end(ret),
std::begin(ys)),
std::end(ys)));
return ret;
}
template <typename T>
auto concat(std::vector<T> const & xs, std::vector<T> && ys)
{
auto ret = xs;
ret.insert(std::end(ret),
std::make_move_iterator(std::begin(ys)),
std::make_move_iterator(std::end(ys)));
return ret;
}
template <typename T>
auto concat(std::vector<T> && xs, std::vector<T> const & ys)
{
auto ret = std::move(xs);
ret.insert(std::end(ret),
std::begin(ys)),
std::end(ys)));
return ret;
}
template <typename T>
auto concat(std::vector<T> && xs, std::vector<T> && ys)
{
auto ret = std::move(xs);
ret.insert(std::end(ret),
std::make_move_iterator(std::begin(ys)),
std::make_move_iterator(std::end(ys)));
return ret;
}
forward_iterator
● Concat example with a single function?
template <typename Vec1, typename Vec2>
auto append(Vec1 && xs, Vec2 && ys)
{
auto ret = std::forward<Vec1>(xs);
ret.insert(std::end(ret),
???(std::begin(ys)),
???(std::end(ys)));
return ret;
}
how to forward these?
forward_iterator
template <typename Vec1, typename Vec2>
auto append(Vec1 && xs, Vec2 && ys)
{
auto ret = std::forward<Vec1>(xs);
ret.insert(std::end(ret),
cat::forward_iterator<Vec2>(std::begin(ys)),
cat::forward_iterator<Vec2>(std::end(ys)));
return ret;
}
forward_iterator
template <typename Iter>
auto forward_iterator_impl(Iter it, std::true_type)
{ return it; }
template <typename Iter>
auto forward_iterator_impl(Iter it, std::false_type)
{ return std::make_move_iterator(it); }
template <typename Ref, typename Iter>
auto forward_iterator(Iter it)
{
return forward_iterator_impl(std::move(it), std::is_lvalue_reference<Ref>{});
}
Curry functional utility
● Cat provides a callable type generated by curry function
which supports:
○ partial application, composition and lazy evaluation
auto f = [](int a, int b) { return a+b; };
auto g = [](int a) { return a+1; };
auto f_ = cat::curry(f);
auto g_ = cat::curry(g);
cout << f_(1)(2);
int c = f_(1,2);
auto l = f_.apply(1,2); // lazy evaluation
c += l();
Additional functional utilities...
● Functional composition (math style)
auto h = f_ ^ g_;
cout << h(1,2); // > 4
● Argument flipping
auto g = cat::flip(f);
● Infix on operator
vector<pair<int, string>> vec = { {2, “world”}, {2, “hello”} };
sort(begin(xs), end(xs), less<int>{} |on| first);
cat callable and curry
● FP does not encourage passing arguments by L-value ref.
○ however Cat library is able to handle them.
● Is the callable type generated by curry a closure? Maybe
○ If the argument of the target function is an L-value ref. then an L-value ref. is
stored into the callable.
○ A copy of the decayed argument is stored otherwise.
● What are the implications?
○ because the callable may hold an L-value reference, an undefined behavior is expected if
it is evaluated with the referred arguments expired
○ the behavior mimics perfectly that of the target function
cat callables vs. std bind
cat::curry
auto f = [](int a, int &b) {
++b; return a+b;
};
int n = 0;
auto f_ = cat::curry(f)(1);
std::cout << f_(n) << std::endl;
std::cout << n << std::endl;
std::bind
auto f = [](int a, int &b) {
++b; return a+b;
};
int n = 0;
auto f_ = std::bind(f, 1, _1);
std::cout << f_(n) << std::endl;
std::cout << n << std::endl;
cat callables vs. std bind
cat::curry
auto f = [](int a, int &b) {
++b; return a+b;
};
int n = 0;
auto f_ = cat::curry(f)(1);
std::cout << f_(n) << std::endl;
std::cout << n << std::endl;
> 2
> 1
std::bind
auto f = [](int a, int &b) {
++b; return a+b;
};
int n = 0;
auto f_ = std::bind(f, 1, _1);
std::cout << f_(n) << std::endl;
std::cout << n << std::endl;
> 2
> 1
OK OK
cat callables vs. std bind
cat::curry
auto f = [](int &a, int b) {
++a; return a+b;
};
int n = 0;
auto f_ = cat::curry(f)(n);
std::cout << f_(1) << std::endl;
std::cout << n << std::endl;
std::bind
auto f = [](int &a, int b) {
++a; return a+b;
};
int n = 0;
auto f_ = std::bind(f, n, _1);
std::cout << f_(1) << std::endl;
std::cout << n << std::endl;
cat callables vs. std bind
cat::curry
auto f = [](int &a, int b) {
++a; return a+b;
};
int n = 0;
auto f_ = cat::curry(f)(n);
std::cout << f_(1) << std::endl;
std::cout << n << std::endl;
> 2
> 1
std::bind
auto f = [](int &a, int b) {
++a; return a+b;
};
int n = 0;
auto f_ = std::bind(f, n, _1);
std::cout << f_(1) << std::endl;
std::cout << n << std::endl;
> 2
> 0
store with decay
perfect forwarding
unspecified
unspecified
OK
what’s going on
here?!?
Type classes
Type classes
● Type class is a type system construct that supports ad
hoc polymorphism
○ In other words a type class is a collection of types with a common property…
● Why type classes are useful in C++?
○ type classes pose rules for overloading and generic programming
■ from the perspective of error handling
○ can be used effectively with concepts
● The Haskell language Eq typeclass
○ A very basic type-class is Eq with == and /=
○ A type is an instance of Eq typeclass if it does support ==, /= operators
Typeclassiopedia
Typeclassiopedia
● Show typeclass is useful for debugging, it provides the function show that
converts a type into a string:
std::string show(T const &);
● Each C++ standard type has an instance of show:
○ fundamental types, arrays, containers, pair, tuples, pointers, chrono types, optional and
string_view, etc.
● It’s possible to declare new instances of show:
○ a new or existing type becomes showable
○ is_showable<T> type traits is generated automatically and can be used in TMP, concepts,
static_asserts, etc…
Show type-class
template <typename T>
struct Show
{ virtual std::string show(T const &) = 0;
};
template <typename T> struct ShowInstance;
template <typename T>
inline std::string show(T const &v)
{
static_assert(is_showable<T>::value, "T is not showable!");
return ShowInstance<T>{}.show(v);
}
template <typename T>
struct is_showable : has_specialization<ShowInstance, T> { };
Show type-class
Base instance
Useful type trait
free function
Type class
Show instances...
template <typename T>
struct ShowInstance<int> final : Show<int>
{
std::string
show(const int &value) override
{ return std::to_string(value); }
};
template <typename T>
struct ShowInstance<bool> final : Show<bool>
{
std::string
show(const bool &value) override
{ return value ? “true” : “false”;}
};
bool
int
Show instances...
template <typename T>
struct ShowInstance<int> final : Show<int>
{
std::string
show(const int &value) override
{ return std::to_string(value); }
};
template <typename T>
struct ShowInstance<bool> final : Show<bool>
{
std::string
show(const bool &value) override
{ return value ? “true” : “false”;}
};
bool
int
template <typename T>
void print_(T const &elem)
{
std::cout << show(elem) << std::endl;
};
print_(42);
print_(make_tuple(2.718281, "Hello World!", nullopt));
print_(vector<int>{1,2,3});
42
( 2.718281 "Hello World!" () )
[ 1 2 3 ]
Show instances...
template <typename T>
struct ShowInstance<optional<T>> final : Show<optional<T>>
{
std::string
show(const optional<T> &t) override
{
if (t) return std::string(1,’(‘) + cat::show(t.value()) + ')';
return "()";
}
};
template <>
struct ShowInstance<nullopt_t> final : Show<nullopt_t>
{
std::string show(const nullopt_t &) override
{ return "()"; }
};
optional<T>
nullopt_t
Read type-class
template <typename T>
struct Read
{
virtual optional<pair<T, string_view>> reads(string_view) = 0;
};
Type class
Read type-class
template <typename T>
struct Read
{
virtual optional<pair<T, string_view>> reads(string_view) = 0;
};
Type class
const char * s = “13 42”;
if (auto x = reads<int>(s)) {
if (auto y = reads<int>(x->second)) {
cout << show(x) << ' ' << show(y) << endl;
}}
((13 " 42")) ((42 ""))
Functor
● Functor is a class for types which can be mapped over (haskell-
wikibooks)
○ It has a single method (high-order function) called fmap.
● The most intuitive example of functor is that of a box
○ fmap takes a function from apples to eggs (Apple -> Egg), a box of apples and
returns a box of eggs
● A functor is any kind of type constructor that can contain a type
○ in C++ a container, an optional, a smart pointer etc. is a functor
■ functor properties for them are satisfied
○ with fmap that is able to apply a function over
Functor type-class
template <template <typename ...> class F>
struct Functor
{
template <typename A, typename Fun, typename Fa_>
struct where
{
virtual auto fmap(Fun fun, Fa_ && fa) -> F<std::result_of_t<Fun(A)>> = 0;
};
};
template <typename Fun, typename Fa_>
auto operator()(Fun f, Fa_ && xs) const
{
static_assert(..., "Type not a functor!");
return FunctorInstance<std::decay_t<Fa_>, Fun, Fa_>{}.fmap(std::move(f), std::forward<Fa_>(xs));
}
template template argument
virtual template method
return type deduction
is this a forwarding reference!?!?
Functor instance
template <typename A, typename Fun, typename Fa_>
struct FunctorInstance<std::vector<A>, Fun, Fa_> final :
Functor<std::vector>::template where<A, Fun, Fa_>
{
using B = std::result_of_t<Fun(A)>;
std::vector<B>
fmap(Fun f, Fa_ && xs) override
{
std::vector<B> out;
out.reserve(xs.size());
for(auto & x : xs)
out.push_back(f(cat::forward_as<Fa_>(x)));
return out;
}
};
return type deduction
is this a forwarding reference!?!?
Functor instance
template <typename A, typename Fun, typename Fa_>
struct FunctorInstance<std::vector<A>, Fun, Fa_> final :
Functor<std::vector>::template where<A, Fun, Fa_>
{
using B = std::result_of_t<Fun(A)>;
std::vector<B>
fmap(Fun f, Fa_ && xs) override
{
std::vector<B> out;
out.reserve(xs.size());
for(auto & x : xs)
out.push_back(f(cat::forward_as<Fa_>(x)));
return out;
}
};
is this a forwarding reference!?!?
vector<string> v = {"hello", "world"};
auto s = fmap([](string const &s) { return s.size(); }, v);
cout << show (v) << endl;
cout << show (s) << endl;
[ "hello" "world" ]
[ 5 5 ]
return type deduction
Home page
https://http://cat.github.io/
Get the code!
git clone https://github.com/cat/cat.git
Volunteers?
nicola@pfq.io

Weitere ähnliche Inhalte

Was ist angesagt?

What can scala puzzlers teach us
What can scala puzzlers teach usWhat can scala puzzlers teach us
What can scala puzzlers teach usDaniel Sobral
 
Peyton jones-2011-type classes
Peyton jones-2011-type classesPeyton jones-2011-type classes
Peyton jones-2011-type classesTakayuki Muranushi
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slideTakayuki Muranushi
 
Testing for share
Testing for share Testing for share
Testing for share Rajeev Mehta
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scalaehsoon
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosBrian Cardiff
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
javaimplementation
javaimplementationjavaimplementation
javaimplementationFaRaz Ahmad
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basicsmhtspvtltd
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operatorsNico Ludwig
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingYusuke Miyazaki
 

Was ist angesagt? (20)

What can scala puzzlers teach us
What can scala puzzlers teach usWhat can scala puzzlers teach us
What can scala puzzlers teach us
 
Peyton jones-2011-type classes
Peyton jones-2011-type classesPeyton jones-2011-type classes
Peyton jones-2011-type classes
 
Peyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slidePeyton jones-2009-fun with-type_functions-slide
Peyton jones-2009-fun with-type_functions-slide
 
Testing for share
Testing for share Testing for share
Testing for share
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
 
Crystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafiosCrystal: tipos, peculiaridades y desafios
Crystal: tipos, peculiaridades y desafios
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Java Generics
Java GenericsJava Generics
Java Generics
 
The Future of C++
The Future of C++The Future of C++
The Future of C++
 
Scala qq
Scala qqScala qq
Scala qq
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
javaimplementation
javaimplementationjavaimplementation
javaimplementation
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Core Java Basics
Core Java BasicsCore Java Basics
Core Java Basics
 
(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators(5) cpp abstractions essential_operators
(5) cpp abstractions essential_operators
 
Scala
ScalaScala
Scala
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner Typing
 
06. haskell type builder
06. haskell type builder06. haskell type builder
06. haskell type builder
 
Typeclasses
TypeclassesTypeclasses
Typeclasses
 

Andere mochten auch

Functional approach to packet processing
Functional approach to packet processingFunctional approach to packet processing
Functional approach to packet processingNicola Bonelli
 
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa IT
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa ITSCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa IT
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa ITRedge Technologies
 
100 M pakietów na sekundę dla każdego.
100 M pakietów na sekundę dla każdego. 100 M pakietów na sekundę dla każdego.
100 M pakietów na sekundę dla każdego. Redge Technologies
 
Anatomy powerpoint final
Anatomy powerpoint finalAnatomy powerpoint final
Anatomy powerpoint finalDerek Baad
 
100Mpps czyli jak radzić sobie z atakami DDoS?
100Mpps czyli jak radzić sobie z atakami DDoS?100Mpps czyli jak radzić sobie z atakami DDoS?
100Mpps czyli jak radzić sobie z atakami DDoS?Redge Technologies
 
Presentation
PresentationPresentation
Presentationbugway
 
Presentation for Advanced Detection and Remote Sensing: Radar Systems
Presentation for Advanced Detection and Remote Sensing:  Radar SystemsPresentation for Advanced Detection and Remote Sensing:  Radar Systems
Presentation for Advanced Detection and Remote Sensing: Radar Systemsgtogtema
 
MedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS
 
Infographic: The Dutch Games Market
Infographic: The Dutch Games MarketInfographic: The Dutch Games Market
Infographic: The Dutch Games MarketIngenico ePayments
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubileeguestc8e3279
 
2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwellsRichard Ovenden
 
FactorEx - электронный факторинг
FactorEx - электронный факторинг FactorEx - электронный факторинг
FactorEx - электронный факторинг E-COM UA
 
Anatomy of a Cat
Anatomy of a Cat Anatomy of a Cat
Anatomy of a Cat melbel93
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets AppJamesCaan
 
Cat anatomy
Cat anatomyCat anatomy
Cat anatomyteywin
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstractionSergey Platonov
 

Andere mochten auch (20)

Functional approach to packet processing
Functional approach to packet processingFunctional approach to packet processing
Functional approach to packet processing
 
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa IT
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa ITSCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa IT
SCAP – standaryzacja formatów wymiany danych w zakresie bezpieczeństwa IT
 
100 M pakietów na sekundę dla każdego.
100 M pakietów na sekundę dla każdego. 100 M pakietów na sekundę dla każdego.
100 M pakietów na sekundę dla każdego.
 
Anatomy powerpoint final
Anatomy powerpoint finalAnatomy powerpoint final
Anatomy powerpoint final
 
100Mpps czyli jak radzić sobie z atakami DDoS?
100Mpps czyli jak radzić sobie z atakami DDoS?100Mpps czyli jak radzić sobie z atakami DDoS?
100Mpps czyli jak radzić sobie z atakami DDoS?
 
100 M pps on PC.
100 M pps on PC.100 M pps on PC.
100 M pps on PC.
 
Presentation
PresentationPresentation
Presentation
 
JS patterns
JS patternsJS patterns
JS patterns
 
Presentation for Advanced Detection and Remote Sensing: Radar Systems
Presentation for Advanced Detection and Remote Sensing:  Radar SystemsPresentation for Advanced Detection and Remote Sensing:  Radar Systems
Presentation for Advanced Detection and Remote Sensing: Radar Systems
 
MedicReS Animal Experiments
MedicReS Animal ExperimentsMedicReS Animal Experiments
MedicReS Animal Experiments
 
Week10
Week10Week10
Week10
 
Infographic: The Dutch Games Market
Infographic: The Dutch Games MarketInfographic: The Dutch Games Market
Infographic: The Dutch Games Market
 
2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee2010 A Strategic Year Of The Jubilee
2010 A Strategic Year Of The Jubilee
 
2010 bodley and blackwells
2010 bodley and blackwells2010 bodley and blackwells
2010 bodley and blackwells
 
RAII and ScopeGuard
RAII and ScopeGuardRAII and ScopeGuard
RAII and ScopeGuard
 
FactorEx - электронный факторинг
FactorEx - электронный факторинг FactorEx - электронный факторинг
FactorEx - электронный факторинг
 
Anatomy of a Cat
Anatomy of a Cat Anatomy of a Cat
Anatomy of a Cat
 
James Caan Business Secrets App
James Caan Business Secrets AppJames Caan Business Secrets App
James Caan Business Secrets App
 
Cat anatomy
Cat anatomyCat anatomy
Cat anatomy
 
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
Gor Nishanov,  C++ Coroutines – a negative overhead abstractionGor Nishanov,  C++ Coroutines – a negative overhead abstraction
Gor Nishanov, C++ Coroutines – a negative overhead abstraction
 

Ähnlich wie Cat's anatomy

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template LibraryIlio Catallo
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0Yaser Zhian
 
ANSI C REFERENCE CARD
ANSI C REFERENCE CARDANSI C REFERENCE CARD
ANSI C REFERENCE CARDTia Ricci
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowScala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowLightbend
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt FaluoticoWithTheBest
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Sheik Uduman Ali
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants Hemantha Kulathilake
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seoJinTaek Seo
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++•sreejith •sree
 

Ähnlich wie Cat's anatomy (20)

C++ Standard Template Library
C++ Standard Template LibraryC++ Standard Template Library
C++ Standard Template Library
 
C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0C++11 - A Change in Style - v2.0
C++11 - A Change in Style - v2.0
 
ANSI C REFERENCE CARD
ANSI C REFERENCE CARDANSI C REFERENCE CARD
ANSI C REFERENCE CARD
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
C# programming
C# programming C# programming
C# programming
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Templates2
Templates2Templates2
Templates2
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Session 4
Session 4Session 4
Session 4
 
Scala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To KnowScala 3 Is Coming: Martin Odersky Shares What To Know
Scala 3 Is Coming: Martin Odersky Shares What To Know
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
 
Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants COM1407: Type Casting, Command Line Arguments and Defining Constants
COM1407: Type Casting, Command Line Arguments and Defining Constants
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo01 stack 20160908_jintaek_seo
01 stack 20160908_jintaek_seo
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 

Kürzlich hochgeladen

Immunoblott technique for protein detection.ppt
Immunoblott technique for protein detection.pptImmunoblott technique for protein detection.ppt
Immunoblott technique for protein detection.pptAmirRaziq1
 
FBI Profiling - Forensic Psychology.pptx
FBI Profiling - Forensic Psychology.pptxFBI Profiling - Forensic Psychology.pptx
FBI Profiling - Forensic Psychology.pptxPayal Shrivastava
 
3.-Acknowledgment-Dedication-Abstract.docx
3.-Acknowledgment-Dedication-Abstract.docx3.-Acknowledgment-Dedication-Abstract.docx
3.-Acknowledgment-Dedication-Abstract.docxUlahVanessaBasa
 
Production technology of Brinjal -Solanum melongena
Production technology of Brinjal -Solanum melongenaProduction technology of Brinjal -Solanum melongena
Production technology of Brinjal -Solanum melongenajana861314
 
6.2 Pests of Sesame_Identification_Binomics_Dr.UPR
6.2 Pests of Sesame_Identification_Binomics_Dr.UPR6.2 Pests of Sesame_Identification_Binomics_Dr.UPR
6.2 Pests of Sesame_Identification_Binomics_Dr.UPRPirithiRaju
 
bonjourmadame.tumblr.com bhaskar's girls
bonjourmadame.tumblr.com bhaskar's girlsbonjourmadame.tumblr.com bhaskar's girls
bonjourmadame.tumblr.com bhaskar's girlshansessene
 
GLYCOSIDES Classification Of GLYCOSIDES Chemical Tests Glycosides
GLYCOSIDES Classification Of GLYCOSIDES  Chemical Tests GlycosidesGLYCOSIDES Classification Of GLYCOSIDES  Chemical Tests Glycosides
GLYCOSIDES Classification Of GLYCOSIDES Chemical Tests GlycosidesNandakishor Bhaurao Deshmukh
 
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learning
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep LearningCombining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learning
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learningvschiavoni
 
Oxo-Acids of Halogens and their Salts.pptx
Oxo-Acids of Halogens and their Salts.pptxOxo-Acids of Halogens and their Salts.pptx
Oxo-Acids of Halogens and their Salts.pptxfarhanvvdk
 
Introduction of Organ-On-A-Chip - Creative Biolabs
Introduction of Organ-On-A-Chip - Creative BiolabsIntroduction of Organ-On-A-Chip - Creative Biolabs
Introduction of Organ-On-A-Chip - Creative BiolabsCreative-Biolabs
 
Science (Communication) and Wikipedia - Potentials and Pitfalls
Science (Communication) and Wikipedia - Potentials and PitfallsScience (Communication) and Wikipedia - Potentials and Pitfalls
Science (Communication) and Wikipedia - Potentials and PitfallsDobusch Leonhard
 
Pests of Sunflower_Binomics_Identification_Dr.UPR
Pests of Sunflower_Binomics_Identification_Dr.UPRPests of Sunflower_Binomics_Identification_Dr.UPR
Pests of Sunflower_Binomics_Identification_Dr.UPRPirithiRaju
 
cybrids.pptx production_advanges_limitation
cybrids.pptx production_advanges_limitationcybrids.pptx production_advanges_limitation
cybrids.pptx production_advanges_limitationSanghamitraMohapatra5
 
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdf
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdfKDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdf
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdfGABYFIORELAMALPARTID1
 
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survival
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's SurvivalHarry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survival
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survivalkevin8smith
 
Total Legal: A “Joint” Journey into the Chemistry of Cannabinoids
Total Legal: A “Joint” Journey into the Chemistry of CannabinoidsTotal Legal: A “Joint” Journey into the Chemistry of Cannabinoids
Total Legal: A “Joint” Journey into the Chemistry of CannabinoidsMarkus Roggen
 
whole genome sequencing new and its types including shortgun and clone by clone
whole genome sequencing new  and its types including shortgun and clone by clonewhole genome sequencing new  and its types including shortgun and clone by clone
whole genome sequencing new and its types including shortgun and clone by clonechaudhary charan shingh university
 
Telephone Traffic Engineering Online Lec
Telephone Traffic Engineering Online LecTelephone Traffic Engineering Online Lec
Telephone Traffic Engineering Online Lecfllcampolet
 
Introduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxIntroduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxMedical College
 
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPRPirithiRaju
 

Kürzlich hochgeladen (20)

Immunoblott technique for protein detection.ppt
Immunoblott technique for protein detection.pptImmunoblott technique for protein detection.ppt
Immunoblott technique for protein detection.ppt
 
FBI Profiling - Forensic Psychology.pptx
FBI Profiling - Forensic Psychology.pptxFBI Profiling - Forensic Psychology.pptx
FBI Profiling - Forensic Psychology.pptx
 
3.-Acknowledgment-Dedication-Abstract.docx
3.-Acknowledgment-Dedication-Abstract.docx3.-Acknowledgment-Dedication-Abstract.docx
3.-Acknowledgment-Dedication-Abstract.docx
 
Production technology of Brinjal -Solanum melongena
Production technology of Brinjal -Solanum melongenaProduction technology of Brinjal -Solanum melongena
Production technology of Brinjal -Solanum melongena
 
6.2 Pests of Sesame_Identification_Binomics_Dr.UPR
6.2 Pests of Sesame_Identification_Binomics_Dr.UPR6.2 Pests of Sesame_Identification_Binomics_Dr.UPR
6.2 Pests of Sesame_Identification_Binomics_Dr.UPR
 
bonjourmadame.tumblr.com bhaskar's girls
bonjourmadame.tumblr.com bhaskar's girlsbonjourmadame.tumblr.com bhaskar's girls
bonjourmadame.tumblr.com bhaskar's girls
 
GLYCOSIDES Classification Of GLYCOSIDES Chemical Tests Glycosides
GLYCOSIDES Classification Of GLYCOSIDES  Chemical Tests GlycosidesGLYCOSIDES Classification Of GLYCOSIDES  Chemical Tests Glycosides
GLYCOSIDES Classification Of GLYCOSIDES Chemical Tests Glycosides
 
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learning
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep LearningCombining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learning
Combining Asynchronous Task Parallelism and Intel SGX for Secure Deep Learning
 
Oxo-Acids of Halogens and their Salts.pptx
Oxo-Acids of Halogens and their Salts.pptxOxo-Acids of Halogens and their Salts.pptx
Oxo-Acids of Halogens and their Salts.pptx
 
Introduction of Organ-On-A-Chip - Creative Biolabs
Introduction of Organ-On-A-Chip - Creative BiolabsIntroduction of Organ-On-A-Chip - Creative Biolabs
Introduction of Organ-On-A-Chip - Creative Biolabs
 
Science (Communication) and Wikipedia - Potentials and Pitfalls
Science (Communication) and Wikipedia - Potentials and PitfallsScience (Communication) and Wikipedia - Potentials and Pitfalls
Science (Communication) and Wikipedia - Potentials and Pitfalls
 
Pests of Sunflower_Binomics_Identification_Dr.UPR
Pests of Sunflower_Binomics_Identification_Dr.UPRPests of Sunflower_Binomics_Identification_Dr.UPR
Pests of Sunflower_Binomics_Identification_Dr.UPR
 
cybrids.pptx production_advanges_limitation
cybrids.pptx production_advanges_limitationcybrids.pptx production_advanges_limitation
cybrids.pptx production_advanges_limitation
 
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdf
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdfKDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdf
KDIGO-2023-CKD-Guideline-Public-Review-Draft_5-July-2023.pdf
 
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survival
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's SurvivalHarry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survival
Harry Coumnas Thinks That Human Teleportation May Ensure Humanity's Survival
 
Total Legal: A “Joint” Journey into the Chemistry of Cannabinoids
Total Legal: A “Joint” Journey into the Chemistry of CannabinoidsTotal Legal: A “Joint” Journey into the Chemistry of Cannabinoids
Total Legal: A “Joint” Journey into the Chemistry of Cannabinoids
 
whole genome sequencing new and its types including shortgun and clone by clone
whole genome sequencing new  and its types including shortgun and clone by clonewhole genome sequencing new  and its types including shortgun and clone by clone
whole genome sequencing new and its types including shortgun and clone by clone
 
Telephone Traffic Engineering Online Lec
Telephone Traffic Engineering Online LecTelephone Traffic Engineering Online Lec
Telephone Traffic Engineering Online Lec
 
Introduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptxIntroduction of Human Body & Structure of cell.pptx
Introduction of Human Body & Structure of cell.pptx
 
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR
6.1 Pests of Groundnut_Binomics_Identification_Dr.UPR
 

Cat's anatomy

  • 1. Cat’s anatomy ...overview of a functional library for C++14 Nicola Bonelli <nicola@pfq.io> www.italiancpp.org
  • 3. What is cat? ● Cat is a C++14 functional library inspired by Haskell ● It consists of 97 headers roughly divided into 3 major groups ○ Utilities for the functional programmer ○ Common type-classes ○ Instances of type classes (instances of standard C++ types) ● Is the library mature? ○ No, it is still a work in progress ○ Documentation is still missing… :(
  • 4. To whom is it useful? ● C++ coders that need some utility functions ○ Cat fills the gap of C++ libraries with respect to functional programming, perfect forwarding, tuple manipulation, type traits, etc... ● C++ coders that want to move their first steps toward functional programming ○ if you master functional thinking the pain to switch to Haskell will be relieved ○ conversely, porting projects from Haskell to C++ become much more simple ● Functional thinking improves the quality of C++ code!
  • 5. Library tree ├── cat │ ├── applicative/... │ ├── applicative.hpp │ ├── bifunctor/... │ ├── bifunctor.hpp │ ├── bits/... │ ├── __config.hpp │ ├── container.hpp │ ├── foldable/... │ ├── foldable.hpp │ ├── functional.hpp │ ├── functor/... │ ├── functor.hpp │ ├── infix.hpp │ ├── iterator.hpp │ ├── match.hpp │ ├── meta.hpp │ ├── monad/... │ ├── monad.hpp │ ├── monoid/... │ ├── monoid.hpp │ ├── optional.hpp │ ├── placeholders.hpp │ ├── read/... │ ├── read.hpp │ ├── section.hpp │ ├── show/... │ ├── show.hpp │ ├── string_view.hpp │ ├── tuple.hpp │ ├── type_traits.hpp │ └── utility.hpp ├── example/... │ └── parser/... └── test/... ├── CMakeLists.txt ├── inc/... ├── test/...
  • 6. Utility functions Category Functions functional utilities curry, curry_as, compose (^), flip, on... container fold operations, etc. infix, sections, match utility for infix operators, sections (binary operators), pattern matching... type traits function_type, function_arity, return_type, arg_type_at... perfect forwarding const_forward, forward_as, forward_iterator... tuple make_typle, tuple_assign, tuple_foreach, tuple_map, tuple_apply...
  • 7. Type classes and instances Type-class Instances functor vector, deque, list, forward_list, string, map, multimap, (unordered_*), optional, pair, shared_ptr, unique_ptr, future... bifunctor pair applicative, alternative vector, deque, list, forward_list, optional, pair, shared_ptr, unique_ptr, future... foldable vector, deque, list, forward_list, string, map, multimap, set, multiset, (unordered_*), optional, pair, shared_ptr, unique_ptr...
  • 8. Type classes and instances Type-class Instances monoid vector, deque, list, forward_list, string, map, multimap, set, multiset, (unordered_*), optional, pair, shared_ptr, unique_ptr, future... monad, monad plus vector, deque, list, forward_list, string, optional, shared_ptr, unique_ptr, future... read, show containers, chrono, fundamentals, optional, string types, tuples
  • 10. In functional programming (FP)... ● Function is a first-class citizen ○ it can be passed to or returned from functions ● Functions are composable and support partial application ○ improve code reusability ● Pure functions ○ have no observable side effects ○ referential transparency ● Data immutability ○ concurrent programming
  • 11. Functions and arguments in C++? ● PF encourages a C++ callable type that ○ is pure (does not evaluate on the basis of a global states) ○ does not change the arguments passed ● A pure function can takes arguments by: ○ value ○ const L-value reference ○ R-value reference ○ universal reference (T &&) ● What’s the recommended method?
  • 12. Argument passing comparisons semantic retain ownership pros cons value ● copyable? yes ● non-copyable ? no (need move) ● clean design ● good for sink fun. ● 1 function to maintain ● non copyable object needs to be moved ● non-cheap copyable object is inefficient const L-value ref. ● yes ● ideal interface ● no extra copy/move ● 2^n overloads R-value ref. ● no, but desidered ● good perf. ● 2^n overloads universal ref (T &&) note: (std::vector<T> &&) is not a forwarding reference... ● yes ● no extra copy/move ● 1 function to maintain ● enforce the const L-value ref. ● the argument must be a template ● wrong types passed generate template error hell.
  • 13. Argument passing with perfect forwarding ● Allows to pass both L-value and R-value arguments ● No extra copy or extra move is required ● Allows to retain the ownership of passed objects ○ non-copyable objects does not have to be moved (as req. in pass-by- value) ● If R-value expression is passed then the function can take advantage of it ○ moving elements out of an expiring container
  • 14. Cat general design ● Cat takes advantage of ○ Extensibility ■ instances of a given type are implemented as partial specializations of certain C++ classes ○ Static polymorphism ■ Cat exploits C++ inheritance only to ensure that interfaces are complete (default implementations are possible) ○ Non being OOP ■ free functions (or constexpr callables types) ○ Modern C++ ■ constexpr constructors for building objects at compile time ■ override/final help compiler deals with C++ methods (devirtualization) ■ auto for trailing return type deduction
  • 16. Perfect forwarding ● Universal reference allows to perfect forward expressions from generic functions ○ T && arg ■ T && looks like a R-value ref. (but it is not) ■ yet, arg is an L-value expression. ○ std::forward is used to restore the original type: ■ std::forward<T>(arg) ● T can either be Object& or Object ● Reduce the number of functions to maintain: ○ for each argument one should maintain two versions ■ Object &&arg, and Object const &arg ■ (2^n with the number of arguments) ○ T && can also be used in variadic functions: Ts && ...args
  • 17. Perfect forwarding template <typename F, typename T> auto map(F fun, std::vector<T> const & xs) { … for(auto & x : xs) … = fun(x); template <typename F, typename T> auto map(F fun, std::vector<T> && xs) { … for(auto & x : xs) … = fun(std::move(x));
  • 18. Perfect forwarding template <typename F, typename T> auto map(F fun, std::vector<T> const & xs) { … for(auto & x : xs) … = fun(x); template <typename F, typename T> auto map(F fun, std::vector<T> && xs) { … for(auto & x : xs) … = fun(std::move(x)); template <typename F, typename Vector> auto map(F fun, Vector && xs) { … for(auto & x : xs) … = fun(???(x)); how to forward this?
  • 19. Perfect forwarding template <typename F, typename T> auto map(F fun, std::vector<T> const & xs) { … for(auto & x : xs) … = fun(x); template <typename F, typename T> auto map(F fun, std::vector<T> && xs) { … for(auto & x : xs) … = fun(std::move(x)); template <typename F, typename Vector> auto map(F fun, Vector && xs) { … for(auto & x : xs) … = fun(cat::forward_as<Vector>(x));
  • 20. forward_as ● Forward_as implementation: template<typename T, typename V> decltype(auto) forward_as(V && value) { return static_cast< std::conditional_t< std::is_lvalue_reference<T>::value, std::remove_reference_t<V> &, std::remove_reference_t<V> &&>>(value); }
  • 21. iterator or move_iterator? ● Homework ○ “...write a function that takes two vectors and returns a new one, the result of concatenation.” ● Elements contained could be: ○ cheap to move and expensive to copy ● Suggestion: ○ take into account the L/R value-ness of the vectors passed...
  • 22. iterator or move_iterator? template <typename T> auto concat(std::vector<T> const &xs, std::vector<T> const &ys) { auto ret = xs; ret.insert(std::end(ret), std::begin(ys)), std::end(ys))); return ret; } template <typename T> auto concat(std::vector<T> const & xs, std::vector<T> && ys) { auto ret = xs; ret.insert(std::end(ret), std::make_move_iterator(std::begin(ys)), std::make_move_iterator(std::end(ys))); return ret; } template <typename T> auto concat(std::vector<T> && xs, std::vector<T> const & ys) { auto ret = std::move(xs); ret.insert(std::end(ret), std::begin(ys)), std::end(ys))); return ret; } template <typename T> auto concat(std::vector<T> && xs, std::vector<T> && ys) { auto ret = std::move(xs); ret.insert(std::end(ret), std::make_move_iterator(std::begin(ys)), std::make_move_iterator(std::end(ys))); return ret; }
  • 23. forward_iterator ● Concat example with a single function? template <typename Vec1, typename Vec2> auto append(Vec1 && xs, Vec2 && ys) { auto ret = std::forward<Vec1>(xs); ret.insert(std::end(ret), ???(std::begin(ys)), ???(std::end(ys))); return ret; } how to forward these?
  • 24. forward_iterator template <typename Vec1, typename Vec2> auto append(Vec1 && xs, Vec2 && ys) { auto ret = std::forward<Vec1>(xs); ret.insert(std::end(ret), cat::forward_iterator<Vec2>(std::begin(ys)), cat::forward_iterator<Vec2>(std::end(ys))); return ret; }
  • 25. forward_iterator template <typename Iter> auto forward_iterator_impl(Iter it, std::true_type) { return it; } template <typename Iter> auto forward_iterator_impl(Iter it, std::false_type) { return std::make_move_iterator(it); } template <typename Ref, typename Iter> auto forward_iterator(Iter it) { return forward_iterator_impl(std::move(it), std::is_lvalue_reference<Ref>{}); }
  • 26. Curry functional utility ● Cat provides a callable type generated by curry function which supports: ○ partial application, composition and lazy evaluation auto f = [](int a, int b) { return a+b; }; auto g = [](int a) { return a+1; }; auto f_ = cat::curry(f); auto g_ = cat::curry(g); cout << f_(1)(2); int c = f_(1,2); auto l = f_.apply(1,2); // lazy evaluation c += l();
  • 27. Additional functional utilities... ● Functional composition (math style) auto h = f_ ^ g_; cout << h(1,2); // > 4 ● Argument flipping auto g = cat::flip(f); ● Infix on operator vector<pair<int, string>> vec = { {2, “world”}, {2, “hello”} }; sort(begin(xs), end(xs), less<int>{} |on| first);
  • 28. cat callable and curry ● FP does not encourage passing arguments by L-value ref. ○ however Cat library is able to handle them. ● Is the callable type generated by curry a closure? Maybe ○ If the argument of the target function is an L-value ref. then an L-value ref. is stored into the callable. ○ A copy of the decayed argument is stored otherwise. ● What are the implications? ○ because the callable may hold an L-value reference, an undefined behavior is expected if it is evaluated with the referred arguments expired ○ the behavior mimics perfectly that of the target function
  • 29. cat callables vs. std bind cat::curry auto f = [](int a, int &b) { ++b; return a+b; }; int n = 0; auto f_ = cat::curry(f)(1); std::cout << f_(n) << std::endl; std::cout << n << std::endl; std::bind auto f = [](int a, int &b) { ++b; return a+b; }; int n = 0; auto f_ = std::bind(f, 1, _1); std::cout << f_(n) << std::endl; std::cout << n << std::endl;
  • 30. cat callables vs. std bind cat::curry auto f = [](int a, int &b) { ++b; return a+b; }; int n = 0; auto f_ = cat::curry(f)(1); std::cout << f_(n) << std::endl; std::cout << n << std::endl; > 2 > 1 std::bind auto f = [](int a, int &b) { ++b; return a+b; }; int n = 0; auto f_ = std::bind(f, 1, _1); std::cout << f_(n) << std::endl; std::cout << n << std::endl; > 2 > 1 OK OK
  • 31. cat callables vs. std bind cat::curry auto f = [](int &a, int b) { ++a; return a+b; }; int n = 0; auto f_ = cat::curry(f)(n); std::cout << f_(1) << std::endl; std::cout << n << std::endl; std::bind auto f = [](int &a, int b) { ++a; return a+b; }; int n = 0; auto f_ = std::bind(f, n, _1); std::cout << f_(1) << std::endl; std::cout << n << std::endl;
  • 32. cat callables vs. std bind cat::curry auto f = [](int &a, int b) { ++a; return a+b; }; int n = 0; auto f_ = cat::curry(f)(n); std::cout << f_(1) << std::endl; std::cout << n << std::endl; > 2 > 1 std::bind auto f = [](int &a, int b) { ++a; return a+b; }; int n = 0; auto f_ = std::bind(f, n, _1); std::cout << f_(1) << std::endl; std::cout << n << std::endl; > 2 > 0 store with decay perfect forwarding unspecified unspecified OK what’s going on here?!?
  • 34. Type classes ● Type class is a type system construct that supports ad hoc polymorphism ○ In other words a type class is a collection of types with a common property… ● Why type classes are useful in C++? ○ type classes pose rules for overloading and generic programming ■ from the perspective of error handling ○ can be used effectively with concepts ● The Haskell language Eq typeclass ○ A very basic type-class is Eq with == and /= ○ A type is an instance of Eq typeclass if it does support ==, /= operators
  • 37. ● Show typeclass is useful for debugging, it provides the function show that converts a type into a string: std::string show(T const &); ● Each C++ standard type has an instance of show: ○ fundamental types, arrays, containers, pair, tuples, pointers, chrono types, optional and string_view, etc. ● It’s possible to declare new instances of show: ○ a new or existing type becomes showable ○ is_showable<T> type traits is generated automatically and can be used in TMP, concepts, static_asserts, etc… Show type-class
  • 38. template <typename T> struct Show { virtual std::string show(T const &) = 0; }; template <typename T> struct ShowInstance; template <typename T> inline std::string show(T const &v) { static_assert(is_showable<T>::value, "T is not showable!"); return ShowInstance<T>{}.show(v); } template <typename T> struct is_showable : has_specialization<ShowInstance, T> { }; Show type-class Base instance Useful type trait free function Type class
  • 39. Show instances... template <typename T> struct ShowInstance<int> final : Show<int> { std::string show(const int &value) override { return std::to_string(value); } }; template <typename T> struct ShowInstance<bool> final : Show<bool> { std::string show(const bool &value) override { return value ? “true” : “false”;} }; bool int
  • 40. Show instances... template <typename T> struct ShowInstance<int> final : Show<int> { std::string show(const int &value) override { return std::to_string(value); } }; template <typename T> struct ShowInstance<bool> final : Show<bool> { std::string show(const bool &value) override { return value ? “true” : “false”;} }; bool int template <typename T> void print_(T const &elem) { std::cout << show(elem) << std::endl; }; print_(42); print_(make_tuple(2.718281, "Hello World!", nullopt)); print_(vector<int>{1,2,3}); 42 ( 2.718281 "Hello World!" () ) [ 1 2 3 ]
  • 41. Show instances... template <typename T> struct ShowInstance<optional<T>> final : Show<optional<T>> { std::string show(const optional<T> &t) override { if (t) return std::string(1,’(‘) + cat::show(t.value()) + ')'; return "()"; } }; template <> struct ShowInstance<nullopt_t> final : Show<nullopt_t> { std::string show(const nullopt_t &) override { return "()"; } }; optional<T> nullopt_t
  • 42. Read type-class template <typename T> struct Read { virtual optional<pair<T, string_view>> reads(string_view) = 0; }; Type class
  • 43. Read type-class template <typename T> struct Read { virtual optional<pair<T, string_view>> reads(string_view) = 0; }; Type class const char * s = “13 42”; if (auto x = reads<int>(s)) { if (auto y = reads<int>(x->second)) { cout << show(x) << ' ' << show(y) << endl; }} ((13 " 42")) ((42 ""))
  • 44. Functor ● Functor is a class for types which can be mapped over (haskell- wikibooks) ○ It has a single method (high-order function) called fmap. ● The most intuitive example of functor is that of a box ○ fmap takes a function from apples to eggs (Apple -> Egg), a box of apples and returns a box of eggs ● A functor is any kind of type constructor that can contain a type ○ in C++ a container, an optional, a smart pointer etc. is a functor ■ functor properties for them are satisfied ○ with fmap that is able to apply a function over
  • 45. Functor type-class template <template <typename ...> class F> struct Functor { template <typename A, typename Fun, typename Fa_> struct where { virtual auto fmap(Fun fun, Fa_ && fa) -> F<std::result_of_t<Fun(A)>> = 0; }; }; template <typename Fun, typename Fa_> auto operator()(Fun f, Fa_ && xs) const { static_assert(..., "Type not a functor!"); return FunctorInstance<std::decay_t<Fa_>, Fun, Fa_>{}.fmap(std::move(f), std::forward<Fa_>(xs)); } template template argument virtual template method return type deduction is this a forwarding reference!?!?
  • 46. Functor instance template <typename A, typename Fun, typename Fa_> struct FunctorInstance<std::vector<A>, Fun, Fa_> final : Functor<std::vector>::template where<A, Fun, Fa_> { using B = std::result_of_t<Fun(A)>; std::vector<B> fmap(Fun f, Fa_ && xs) override { std::vector<B> out; out.reserve(xs.size()); for(auto & x : xs) out.push_back(f(cat::forward_as<Fa_>(x))); return out; } }; return type deduction is this a forwarding reference!?!?
  • 47. Functor instance template <typename A, typename Fun, typename Fa_> struct FunctorInstance<std::vector<A>, Fun, Fa_> final : Functor<std::vector>::template where<A, Fun, Fa_> { using B = std::result_of_t<Fun(A)>; std::vector<B> fmap(Fun f, Fa_ && xs) override { std::vector<B> out; out.reserve(xs.size()); for(auto & x : xs) out.push_back(f(cat::forward_as<Fa_>(x))); return out; } }; is this a forwarding reference!?!? vector<string> v = {"hello", "world"}; auto s = fmap([](string const &s) { return s.size(); }, v); cout << show (v) << endl; cout << show (s) << endl; [ "hello" "world" ] [ 5 5 ] return type deduction
  • 48. Home page https://http://cat.github.io/ Get the code! git clone https://github.com/cat/cat.git Volunteers? nicola@pfq.io