SlideShare a Scribd company logo
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
C++11C++11
C++11
C++11C++11
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
Bartlomiej Filipek
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
Sasha Goldshtein
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
Jan 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 Programmer
Raú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++14
Matthieu 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 ALGORITHMS
fawzmasood
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
CyberPlusIndia
 
C++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabsC++17 introduction - Meetup @EtixLabs
C++17 introduction - Meetup @EtixLabs
Stephane 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 overloading2
zindadili
 
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 Scala
Knoldus 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)

Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Extreme Swift
Extreme SwiftExtreme Swift
Extreme Swift
Movel
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
Julie Iskander
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
Baishampayan Ghose
 
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
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario 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 Atencio
Luis Atencio
 
Kotlin coroutines and spring framework
Kotlin coroutines and spring frameworkKotlin coroutines and spring framework
Kotlin coroutines and spring framework
Sunghyouk 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 Examples
Ganesh Samarthyam
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
scalaconfjp
 
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
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
Prashant Kalkar
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
Luis 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-presented
Sumant Tambe
 
Tuning kafka pipelines
Tuning kafka pipelinesTuning kafka pipelines
Tuning kafka pipelines
Sumant 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
 
C++ Coroutines
C++ CoroutinesC++ Coroutines
C++ Coroutines
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 Rx
Sumant Tambe
 
RPC over DDS Beta 1
RPC over DDS Beta 1RPC over DDS Beta 1
RPC over DDS Beta 1
Sumant 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 RxJS
Sumant 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/Subscribe
Sumant 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 Rx
Sumant 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 DDS
Sumant 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 DDS
Sumant 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/Subscribe
Sumant 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 Systems
Sumant Tambe
 
Ph.D. Dissertation
Ph.D. DissertationPh.D. Dissertation
Ph.D. Dissertation
Sumant 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

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
Kartik Tiwari
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
kimdan468
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 

Recently uploaded (20)

Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
Chapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdfChapter -12, Antibiotics (One Page Notes).pdf
Chapter -12, Antibiotics (One Page Notes).pdf
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBCSTRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
STRAND 3 HYGIENIC PRACTICES.pptx GRADE 7 CBC
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.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]; }); }