SlideShare a Scribd company logo
1 of 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)

More Related Content

What's hot

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.
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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)
 

Recently uploaded

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 

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]; }); }