SlideShare une entreprise Scribd logo
1  sur  30
Sumant Tambe, Ph.D.
Microsoft Visual C++ MVP
Senior Software Research Engineer
Real-Time Innovations, Inc.
@sutambe
SFBay Association of C/C++ Users
April 9, 2014
Author
Blogger Open-Source Contributor
LEESA
Rx4DDS.NET
Reflection for DDS-XTypes
» Functional Programming eXchange
» Strange Loop
» ReactConf
» LambdaConf
» LambdaJam
» CraftConf
» MSFT MVP Summit
» Qcon NYC/SF/London
» Closure West
» Spring into Scala
» Progressive F#
» FP Days
» SkillsMatter
» Lambda Expressions
˃ expr.prim.lambda
» Anonymous functions
void abssort(float* x, unsigned N)
{
std::sort(x, x + N,
[](float a, float b) {
return std::abs(a) < std::abs(b);
});
}
class Comp {
float a;
public:
Comp(float x) {
a = x;
}
bool compare(float b) const {
return std::abs(a) < std::abs(b);
}
};
float array[5] = { 0, 1, 2, 3, 4 };
float a = 3;
Comp f(a);
for(float item : array)
std::cout << std::boolalpha << f.compare(item);
class Comp {
float a;
public:
Comp(float x) {
a = x;
}
bool operator () (float b) const {
return std::abs(a) < std::abs(b);
}
};
float array[5] = { 0, 1, 2, 3, 4 };
float a = 3;
Comp f(a);
for(float item : array)
std::cout << std::boolalpha << f(item);
class ##### {
float a;
public:
Foo(float x) {
a = x;
}
bool operator () (float b) const {
return std::abs(a) < std::abs(b);
}
};
float array[5] = { 0, 1, 2, 3, 4 };
float a = 3;
auto f = #####(a);
for(float item : array)
std::cout << std::boolalpha << f(item);
class ##### {
float a;
public:
Foo(float x) {
a = x;
}
bool operator () (float b) const {
return std::abs(a) < std::abs(b);
}
};
float array[5] = { 0, 1, 2, 3, 4 };
float a = 3;
auto f = #####(a);
auto f = [a](float b) { return std::abs(a) < std::abs(b) };
for(float item : array)
std::cout << std::boolalpha << f(item);
» Anonymous functions
» Written exactly in the place where it's needed
» Can access the variables available in the
enclosing scope (closure)
» May maintain state (mutable or const)
» Can be passed to a function
» Can be returned from a function
» Deduce return type automatically
» Accept generic parameter types (only in C++14)
[a](auto b) { return std::abs(a) < std::abs(b) };
» Associative containers and lambdas
» Recursive Lambdas
» Composable list manipulation
» Scope Exit Idiom
» Overloaded Lambdas
» Type Switch (simple pattern matching)
» Converting shared_ptr between boost and std
» In-place parameter pack expansion
» Memoization
» Associative containers: set, map, multiset, multimap
˃ Use comparators
˃ Example, std::set<int, std::less<int>>
» Can comparators be a lambda?
» std::set<int, ???>
» Use std::function as the comparator type
std::set<int, std::function<bool(int, int)>>
numbers([](int i, int j) { return i < j; });
» Small-closure optimization may kick in
˃ Check you compiler manual
auto make_fibo()
{
std::function<int(int)> recurse;
recurse = [&](int n){
return (n<=2)? 1 : recurse(n-1) + recurse(n-2);
};
return recurse;
}
int main() {
auto fibo = make_fibo();
std::cout << fibo(10) << std::endl; // 55
return 0;
}
auto make_fibo()
{
return [](int n) {
std::function<int(int)> recurse;
recurse = [&](int n){
return (n<=2)? 1 : recurse(n-1) + recurse(n-2);
};
return recurse(n);
};
}
int main() {
auto fibo = make_fibo();
std::cout << fibo(10) << std::endl; // 55
return 0;
}
IList<Box> boxes = /* ... */;
int sumOfWeights =
boxes.Where(b => b.Color == Color.RED)
.Select(b => b.Weight)
.Count();
List<Box> boxes = /* ... */;
int sumOfWeights =
boxes.stream()
.filter(b -> b.getColor() == Color.RED)
.map(b -> b.getWeight())
.sum();
C#
Java8
» Example cpplinq (http://cpplinq.codeplex.com)
Box boxes[] = { … };
int sum_of_weights =
cpplinq::from_array(boxes)
>> where([](const Box & box) {
return box.color == Color.RED;
})
>> select([](const Box & box) {
return box.get_weight();
})
>> count();
» Restriction Operators
˃ Where
» Projection Operators
˃ ref, select, select_many
» Partitioning Operators
˃ take, take_while, skip, skip_while
» Join Operators
˃ Join
» Concatenation Operators
˃ Concat
» Ordering Operators
˃ orderby, orderby_ascending or
orderby_descending
» Set Operators
˃ distinct, union_with,
intersect_with, except
» Set Operators
˃ distinct, union_with,
intersect_with, except
» Conversion Operators
˃ to_vector, to_list, to_map,
to_lookup
» Element Operators
˃ first, first_or_default,
last_or_default
» Generation Operators
˃ range, repeat, empty, singleton,
generate,
» Quantifiers
˃ any, all, contains,
» Aggregate Operators
˃ Count, sum, min, max, avg,
aggregate
» Other
˃ pair_wise, zip_with
» Cpplinq http://cpplinq.codeplex.com/
» Narl (Not another range library) https://github.com/essennell/narl
» boost.range http://www.boost.org/doc/libs/1_54_0/libs/range/
» Linq http://pfultz2.github.io/Linq/
» boolinq http://code.google.com/p/boolinq/
» lx++ (part of Native-RX) https://rx.codeplex.com/
» Linq++ https://github.com/hjiang/linqxx/
» oven http://p-stade.sourceforge.net/oven/
» cpplinq (same name but
unrelated) http://code.google.com/p/cpplinq/
» linq https://bitbucket.org/ronag/cppextras/src/master/linq/linq.hp
p
» Language for Embedded
Query and Traversal
» Tree Traversal
˃ For XML data-binding code
generators
˃ Visitors
» Think XPath queries
embedded in C++
˃ Typed (not string encoded)
» Generic Programming
˃ Expression Templates
˃ Meta-programming
˃ C++ Concepts (no longer in C++11)
http://www.dre.vanderbilt.edu/LEESA/
<catalog>
<book>
<title>…</title>
<price>…</price>
<author>
<name>…</name>
<country>…</country>
</author>
</book>
<book>...</book>
...
</catalog>
LEESA:
std::vector<name> author_names =
eval(root, catalog() >> book() >> author() >> name());
XPath: "/book/author/name/text()"
» Find names of authors from USA
» XPath:
“//author[country/text() = ‘USA’]/name/text()”
» LEESA:
Catalog croot = load_catalog(“catalog.xml”);
std::vector<Name> author_names =
eval(croot,
Catalog()
>> DescendantsOf(Catalog(), Author())
>> Select(Author(), [](const Author &a) {
return a.get_country() == “USA”;
})
>> Name());
int main()
{
std::mutex m;
m.lock();
SCOPE_EXIT(m.unlock());
/* Potential exceptions here */
return 0;
}
Example only.
Prefer std::lock_guard
Scope exit idiom ensures that resources are released
template <typename F>
struct ScopeExit {
ScopeExit(F f) : f(f) {}
~ScopeExit() { f(); }
F f;
};
template <typename F>
ScopeExit<F> MakeScopeExit(F f) {
return ScopeExit<F>(f);
};
#define DO_STRING_JOIN(arg1, arg2) arg1 ## arg2
#define SCOPE_EXIT(code) 
auto STRING_JOIN(scope_exit_, __LINE__) =
MakeScopeExit([&](){code;})
» Can you really do that!?
˃ As it turns out, YES!
template <class... F>
struct overload : F... {
overload(F... f) : F(f)... {}
};
template <class... F>
auto make_overload(F... f) {
return overload<F...>(f...);
}
auto f =
make_overload([](int i) { /* print */ },
[](double d) { /* print */ });
f(10); f(9.99);
struct Base {};
struct Derived : Base {};
template <class Poly>
void test(Poly& p) {
match(p)(
[](int i) { cout << “int”; },
[](std::string &) { cout << “string”; },
[](Base &) { cout << "Base"; },
[](Derived &) { cout << "Derived"; },
otherwise([](auto x) { cout << "Otherwise”; })
);
}
test(10); // int
test(std::string(“C++ Truths”)); // string
test(Derived()); // Derived
test(9.99); // Otherwise
» Boost and std::shared_ptr manage memory automatically
» They both use their own reference counters
» What happens when you convert from boost to std shared_ptr
or vice versa
template <typename T>
boost::shared_ptr<T>
make_shared_ptr(std::shared_ptr<T> ptr)
{
return boost::shared_ptr<T>(ptr.get());
}
» Hint: They both support deleters
˃ malloc = allocator
˃ free = deleter
std::shared_ptr<char> buf((char *)malloc(10), free);
template <typename T>
boost::shared_ptr<T>
make_shared_ptr(std::shared_ptr<T> ptr)
{
return boost::shared_ptr<T>(ptr.get(),
[ptr](T*) mutable { ptr.reset(); });
}
template <typename T>
std::shared_ptr<T>
make_shared_ptr(boost::shared_ptr<T> ptr)
{
return std::shared_ptr<T>(ptr.get(),
[ptr](T*) mutable { ptr.reset(); });
}
void no_op(...) { }
template <class... T>
void foreach(T... args)
{
no_op([=](){
cout << args << "n";
return true;
}()...);
}
foreach(10, 20.2, true);
» Avoid repeated calculations by caching function results
template <typename ReturnType, typename... Args>
auto memoize(ReturnType (*func)(Args...))
int fibo(int) { … }
int main()
{
auto mem_fibo = memoize(fibo);
std::cout << “Compute” << mem_fibo(10);
std::cout << “Lookup” << mem_fibo(10);
}
» Avoid repeated calculations by caching function results
template <typename ReturnType,
typename... Args>
auto memoize(ReturnType (*func)(Args...))
{
std::map<std::tuple<Args...>, ReturnType> cache;
return ([=](Args... args) mutable
{
std::tuple<Args...> t(args...);
if (cache.find(t) == cache.end())
{
std::cout << "not foundn";
cache[t] = func(args...);
}
return cache[t];
});
}
Fun with Lambdas: C++14 Style (part 2)

Contenu connexe

Tendances

C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 FeaturesJan Rüegg
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerRaúl Raja Martínez
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14Matthieu Garrigues
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Geeks Anonymes
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMSfawzmasood
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsStephane Gleizes
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Olve Maudal
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2zindadili
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++Neeru Mittal
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 

Tendances (20)

C++11
C++11C++11
C++11
 
C++11
C++11C++11
C++11
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Functional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic ProgrammerFunctional Programming Patterns for the Pragmatic Programmer
Functional Programming Patterns for the Pragmatic Programmer
 
High performance web programming with C++14
High performance web programming with C++14High performance web programming with C++14
High performance web programming with C++14
 
Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)Modern c++ (C++ 11/14)
Modern c++ (C++ 11/14)
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)Modern C++ Explained: Move Semantics (Feb 2018)
Modern C++ Explained: Move Semantics (Feb 2018)
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Library functions in c++
Library functions in c++Library functions in c++
Library functions in c++
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 

Similaire à Fun with Lambdas: C++14 Style (part 2)

Extreme Swift
Extreme SwiftExtreme Swift
Extreme SwiftMovel
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring frameworkSunghyouk Bae
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Chris Adamson
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 

Similaire à Fun with Lambdas: C++14 Style (part 2) (20)

Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
Oh Crap, I Forgot (Or Never Learned) C! [CodeMash 2010]
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Groovy
GroovyGroovy
Groovy
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 

Plus de Sumant Tambe

Kafka tiered-storage-meetup-2022-final-presented
Kafka tiered-storage-meetup-2022-final-presentedKafka tiered-storage-meetup-2022-final-presented
Kafka tiered-storage-meetup-2022-final-presentedSumant Tambe
 
Tuning kafka pipelines
Tuning kafka pipelinesTuning kafka pipelines
Tuning kafka pipelinesSumant Tambe
 
New Tools for a More Functional C++
New Tools for a More Functional C++New Tools for a More Functional C++
New Tools for a More Functional C++Sumant Tambe
 
Reactive Stream Processing in Industrial IoT using DDS and Rx
Reactive Stream Processing in Industrial IoT using DDS and RxReactive Stream Processing in Industrial IoT using DDS and Rx
Reactive Stream Processing in Industrial IoT using DDS and RxSumant Tambe
 
RPC over DDS Beta 1
RPC over DDS Beta 1RPC over DDS Beta 1
RPC over DDS Beta 1Sumant Tambe
 
Remote Log Analytics Using DDS, ELK, and RxJS
Remote Log Analytics Using DDS, ELK, and RxJSRemote Log Analytics Using DDS, ELK, and RxJS
Remote Log Analytics Using DDS, ELK, and RxJSSumant Tambe
 
Property-based Testing and Generators (Lua)
Property-based Testing and Generators (Lua)Property-based Testing and Generators (Lua)
Property-based Testing and Generators (Lua)Sumant Tambe
 
Reactive Stream Processing for Data-centric Publish/Subscribe
Reactive Stream Processing for Data-centric Publish/SubscribeReactive Stream Processing for Data-centric Publish/Subscribe
Reactive Stream Processing for Data-centric Publish/SubscribeSumant Tambe
 
Reactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and RxReactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and RxSumant Tambe
 
An Extensible Architecture for Avionics Sensor Health Assessment Using DDS
An Extensible Architecture for Avionics Sensor Health Assessment Using DDSAn Extensible Architecture for Avionics Sensor Health Assessment Using DDS
An Extensible Architecture for Avionics Sensor Health Assessment Using DDSSumant Tambe
 
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDSOverloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDSSumant Tambe
 
Standardizing the Data Distribution Service (DDS) API for Modern C++
Standardizing the Data Distribution Service (DDS) API for Modern C++Standardizing the Data Distribution Service (DDS) API for Modern C++
Standardizing the Data Distribution Service (DDS) API for Modern C++Sumant Tambe
 
Communication Patterns Using Data-Centric Publish/Subscribe
Communication Patterns Using Data-Centric Publish/SubscribeCommunication Patterns Using Data-Centric Publish/Subscribe
Communication Patterns Using Data-Centric Publish/SubscribeSumant Tambe
 
Retargeting Embedded Software Stack for Many-Core Systems
Retargeting Embedded Software Stack for Many-Core SystemsRetargeting Embedded Software Stack for Many-Core Systems
Retargeting Embedded Software Stack for Many-Core SystemsSumant Tambe
 
Ph.D. Dissertation
Ph.D. DissertationPh.D. Dissertation
Ph.D. DissertationSumant Tambe
 
Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Sumant Tambe
 

Plus de Sumant Tambe (17)

Kafka tiered-storage-meetup-2022-final-presented
Kafka tiered-storage-meetup-2022-final-presentedKafka tiered-storage-meetup-2022-final-presented
Kafka tiered-storage-meetup-2022-final-presented
 
Tuning kafka pipelines
Tuning kafka pipelinesTuning kafka pipelines
Tuning kafka pipelines
 
New Tools for a More Functional C++
New Tools for a More Functional C++New Tools for a More Functional C++
New Tools for a More Functional C++
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
 
Reactive Stream Processing in Industrial IoT using DDS and Rx
Reactive Stream Processing in Industrial IoT using DDS and RxReactive Stream Processing in Industrial IoT using DDS and Rx
Reactive Stream Processing in Industrial IoT using DDS and Rx
 
RPC over DDS Beta 1
RPC over DDS Beta 1RPC over DDS Beta 1
RPC over DDS Beta 1
 
Remote Log Analytics Using DDS, ELK, and RxJS
Remote Log Analytics Using DDS, ELK, and RxJSRemote Log Analytics Using DDS, ELK, and RxJS
Remote Log Analytics Using DDS, ELK, and RxJS
 
Property-based Testing and Generators (Lua)
Property-based Testing and Generators (Lua)Property-based Testing and Generators (Lua)
Property-based Testing and Generators (Lua)
 
Reactive Stream Processing for Data-centric Publish/Subscribe
Reactive Stream Processing for Data-centric Publish/SubscribeReactive Stream Processing for Data-centric Publish/Subscribe
Reactive Stream Processing for Data-centric Publish/Subscribe
 
Reactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and RxReactive Stream Processing Using DDS and Rx
Reactive Stream Processing Using DDS and Rx
 
An Extensible Architecture for Avionics Sensor Health Assessment Using DDS
An Extensible Architecture for Avionics Sensor Health Assessment Using DDSAn Extensible Architecture for Avionics Sensor Health Assessment Using DDS
An Extensible Architecture for Avionics Sensor Health Assessment Using DDS
 
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDSOverloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
 
Standardizing the Data Distribution Service (DDS) API for Modern C++
Standardizing the Data Distribution Service (DDS) API for Modern C++Standardizing the Data Distribution Service (DDS) API for Modern C++
Standardizing the Data Distribution Service (DDS) API for Modern C++
 
Communication Patterns Using Data-Centric Publish/Subscribe
Communication Patterns Using Data-Centric Publish/SubscribeCommunication Patterns Using Data-Centric Publish/Subscribe
Communication Patterns Using Data-Centric Publish/Subscribe
 
Retargeting Embedded Software Stack for Many-Core Systems
Retargeting Embedded Software Stack for Many-Core SystemsRetargeting Embedded Software Stack for Many-Core Systems
Retargeting Embedded Software Stack for Many-Core Systems
 
Ph.D. Dissertation
Ph.D. DissertationPh.D. Dissertation
Ph.D. Dissertation
 
Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)Native XML processing in C++ (BoostCon'11)
Native XML processing in C++ (BoostCon'11)
 

Dernier

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 

Dernier (20)

Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 

Fun with Lambdas: C++14 Style (part 2)

  • 1. Sumant Tambe, Ph.D. Microsoft Visual C++ MVP Senior Software Research Engineer Real-Time Innovations, Inc. @sutambe SFBay Association of C/C++ Users April 9, 2014
  • 3. » Functional Programming eXchange » Strange Loop » ReactConf » LambdaConf » LambdaJam » CraftConf » MSFT MVP Summit » Qcon NYC/SF/London » Closure West » Spring into Scala » Progressive F# » FP Days » SkillsMatter
  • 4. » Lambda Expressions ˃ expr.prim.lambda » Anonymous functions void abssort(float* x, unsigned N) { std::sort(x, x + N, [](float a, float b) { return std::abs(a) < std::abs(b); }); }
  • 5. class Comp { float a; public: Comp(float x) { a = x; } bool compare(float b) const { return std::abs(a) < std::abs(b); } }; float array[5] = { 0, 1, 2, 3, 4 }; float a = 3; Comp f(a); for(float item : array) std::cout << std::boolalpha << f.compare(item);
  • 6. class Comp { float a; public: Comp(float x) { a = x; } bool operator () (float b) const { return std::abs(a) < std::abs(b); } }; float array[5] = { 0, 1, 2, 3, 4 }; float a = 3; Comp f(a); for(float item : array) std::cout << std::boolalpha << f(item);
  • 7. class ##### { float a; public: Foo(float x) { a = x; } bool operator () (float b) const { return std::abs(a) < std::abs(b); } }; float array[5] = { 0, 1, 2, 3, 4 }; float a = 3; auto f = #####(a); for(float item : array) std::cout << std::boolalpha << f(item);
  • 8. class ##### { float a; public: Foo(float x) { a = x; } bool operator () (float b) const { return std::abs(a) < std::abs(b); } }; float array[5] = { 0, 1, 2, 3, 4 }; float a = 3; auto f = #####(a); auto f = [a](float b) { return std::abs(a) < std::abs(b) }; for(float item : array) std::cout << std::boolalpha << f(item);
  • 9. » Anonymous functions » Written exactly in the place where it's needed » Can access the variables available in the enclosing scope (closure) » May maintain state (mutable or const) » Can be passed to a function » Can be returned from a function » Deduce return type automatically » Accept generic parameter types (only in C++14) [a](auto b) { return std::abs(a) < std::abs(b) };
  • 10. » Associative containers and lambdas » Recursive Lambdas » Composable list manipulation » Scope Exit Idiom » Overloaded Lambdas » Type Switch (simple pattern matching) » Converting shared_ptr between boost and std » In-place parameter pack expansion » Memoization
  • 11. » Associative containers: set, map, multiset, multimap ˃ Use comparators ˃ Example, std::set<int, std::less<int>> » Can comparators be a lambda? » std::set<int, ???> » Use std::function as the comparator type std::set<int, std::function<bool(int, int)>> numbers([](int i, int j) { return i < j; }); » Small-closure optimization may kick in ˃ Check you compiler manual
  • 12. auto make_fibo() { std::function<int(int)> recurse; recurse = [&](int n){ return (n<=2)? 1 : recurse(n-1) + recurse(n-2); }; return recurse; } int main() { auto fibo = make_fibo(); std::cout << fibo(10) << std::endl; // 55 return 0; }
  • 13. auto make_fibo() { return [](int n) { std::function<int(int)> recurse; recurse = [&](int n){ return (n<=2)? 1 : recurse(n-1) + recurse(n-2); }; return recurse(n); }; } int main() { auto fibo = make_fibo(); std::cout << fibo(10) << std::endl; // 55 return 0; }
  • 14. IList<Box> boxes = /* ... */; int sumOfWeights = boxes.Where(b => b.Color == Color.RED) .Select(b => b.Weight) .Count(); List<Box> boxes = /* ... */; int sumOfWeights = boxes.stream() .filter(b -> b.getColor() == Color.RED) .map(b -> b.getWeight()) .sum(); C# Java8
  • 15. » Example cpplinq (http://cpplinq.codeplex.com) Box boxes[] = { … }; int sum_of_weights = cpplinq::from_array(boxes) >> where([](const Box & box) { return box.color == Color.RED; }) >> select([](const Box & box) { return box.get_weight(); }) >> count();
  • 16. » Restriction Operators ˃ Where » Projection Operators ˃ ref, select, select_many » Partitioning Operators ˃ take, take_while, skip, skip_while » Join Operators ˃ Join » Concatenation Operators ˃ Concat » Ordering Operators ˃ orderby, orderby_ascending or orderby_descending » Set Operators ˃ distinct, union_with, intersect_with, except » Set Operators ˃ distinct, union_with, intersect_with, except » Conversion Operators ˃ to_vector, to_list, to_map, to_lookup » Element Operators ˃ first, first_or_default, last_or_default » Generation Operators ˃ range, repeat, empty, singleton, generate, » Quantifiers ˃ any, all, contains, » Aggregate Operators ˃ Count, sum, min, max, avg, aggregate » Other ˃ pair_wise, zip_with
  • 17. » Cpplinq http://cpplinq.codeplex.com/ » Narl (Not another range library) https://github.com/essennell/narl » boost.range http://www.boost.org/doc/libs/1_54_0/libs/range/ » Linq http://pfultz2.github.io/Linq/ » boolinq http://code.google.com/p/boolinq/ » lx++ (part of Native-RX) https://rx.codeplex.com/ » Linq++ https://github.com/hjiang/linqxx/ » oven http://p-stade.sourceforge.net/oven/ » cpplinq (same name but unrelated) http://code.google.com/p/cpplinq/ » linq https://bitbucket.org/ronag/cppextras/src/master/linq/linq.hp p
  • 18. » Language for Embedded Query and Traversal » Tree Traversal ˃ For XML data-binding code generators ˃ Visitors » Think XPath queries embedded in C++ ˃ Typed (not string encoded) » Generic Programming ˃ Expression Templates ˃ Meta-programming ˃ C++ Concepts (no longer in C++11) http://www.dre.vanderbilt.edu/LEESA/
  • 20. » Find names of authors from USA » XPath: “//author[country/text() = ‘USA’]/name/text()” » LEESA: Catalog croot = load_catalog(“catalog.xml”); std::vector<Name> author_names = eval(croot, Catalog() >> DescendantsOf(Catalog(), Author()) >> Select(Author(), [](const Author &a) { return a.get_country() == “USA”; }) >> Name());
  • 21. int main() { std::mutex m; m.lock(); SCOPE_EXIT(m.unlock()); /* Potential exceptions here */ return 0; } Example only. Prefer std::lock_guard Scope exit idiom ensures that resources are released
  • 22. template <typename F> struct ScopeExit { ScopeExit(F f) : f(f) {} ~ScopeExit() { f(); } F f; }; template <typename F> ScopeExit<F> MakeScopeExit(F f) { return ScopeExit<F>(f); }; #define DO_STRING_JOIN(arg1, arg2) arg1 ## arg2 #define SCOPE_EXIT(code) auto STRING_JOIN(scope_exit_, __LINE__) = MakeScopeExit([&](){code;})
  • 23. » Can you really do that!? ˃ As it turns out, YES! template <class... F> struct overload : F... { overload(F... f) : F(f)... {} }; template <class... F> auto make_overload(F... f) { return overload<F...>(f...); } auto f = make_overload([](int i) { /* print */ }, [](double d) { /* print */ }); f(10); f(9.99);
  • 24. struct Base {}; struct Derived : Base {}; template <class Poly> void test(Poly& p) { match(p)( [](int i) { cout << “int”; }, [](std::string &) { cout << “string”; }, [](Base &) { cout << "Base"; }, [](Derived &) { cout << "Derived"; }, otherwise([](auto x) { cout << "Otherwise”; }) ); } test(10); // int test(std::string(“C++ Truths”)); // string test(Derived()); // Derived test(9.99); // Otherwise
  • 25. » Boost and std::shared_ptr manage memory automatically » They both use their own reference counters » What happens when you convert from boost to std shared_ptr or vice versa template <typename T> boost::shared_ptr<T> make_shared_ptr(std::shared_ptr<T> ptr) { return boost::shared_ptr<T>(ptr.get()); } » Hint: They both support deleters ˃ malloc = allocator ˃ free = deleter std::shared_ptr<char> buf((char *)malloc(10), free);
  • 26. template <typename T> boost::shared_ptr<T> make_shared_ptr(std::shared_ptr<T> ptr) { return boost::shared_ptr<T>(ptr.get(), [ptr](T*) mutable { ptr.reset(); }); } template <typename T> std::shared_ptr<T> make_shared_ptr(boost::shared_ptr<T> ptr) { return std::shared_ptr<T>(ptr.get(), [ptr](T*) mutable { ptr.reset(); }); }
  • 27. void no_op(...) { } template <class... T> void foreach(T... args) { no_op([=](){ cout << args << "n"; return true; }()...); } foreach(10, 20.2, true);
  • 28. » Avoid repeated calculations by caching function results template <typename ReturnType, typename... Args> auto memoize(ReturnType (*func)(Args...)) int fibo(int) { … } int main() { auto mem_fibo = memoize(fibo); std::cout << “Compute” << mem_fibo(10); std::cout << “Lookup” << mem_fibo(10); }
  • 29. » Avoid repeated calculations by caching function results template <typename ReturnType, typename... Args> auto memoize(ReturnType (*func)(Args...)) { std::map<std::tuple<Args...>, ReturnType> cache; return ([=](Args... args) mutable { std::tuple<Args...> t(args...); if (cache.find(t) == cache.end()) { std::cout << "not foundn"; cache[t] = func(args...); } return cache[t]; }); }