SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
Sumant Tambe, Ph.D.
Microsoft Visual C++ MVP
Senior Software Research Engineer
Real-Time Innovations, Inc.
@sutambe
SFBay Association of C/C++ Users
March 12, 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) };
Thanks to Douglas Crockford. Link to Doug’s JavaScript talk
Write an Identity function that takes
an argument and returns the same
argument.
Identity(3) //3
auto Identity = [](auto x) {
return x;
};
Write 3 functions add, sub, and mul
that take 2 parameters each and return
their sum, difference, and product
respectively.
add(3, 4) // 7
sub(4, 3) // 1
mul(4, 5) // 20
auto add = [](auto x, auto y) {
return x + y;
};
auto sub = [](auto x, auto y) {
return x - y;
};
int mul (int x, int y) {
return x * y;
};
Write a function, identityf, that
takes an argument and returns a
callable that returns that argument
auto idf = identityf(5);
idf() // 5
auto identityf = [](auto x) {
class Inner {
int x;
public: Inner(int i): x(i) {}
int operator() () { return x; }
};
return Inner(x);
};
auto idf = identityf(5);
idf() // 5
auto identityf = [](auto x) {
return [](){ /* must remember x */ };
};
auto identityf = [](auto x) {
return [=]() { return x; };
};
auto idf = identityf(5);
idf() // 5
» A lambda is just an anonymous function.
» A closure is a function which closes over the
environment in which it was defined.
» Not all closures are lambdas and not all
lambdas are closures.
» Closures are just function objects in C++
» C++ closures do not extend the lifetime of their
context. (If you need this use shared_ptr)
Write a function that produces a
function that returns values in a range
fromto(0, 10)
auto fromto = [](auto start, auto finish) {
return
};
auto range = fromto(0, 10)
range() // 0
range() // 1
[=]() mutable {
if(start < finish)
return start++;
else
throw std::runtime_error(“Complete");
};
Write a function that adds from two
invocations
addf(5)(4) // 9
auto addf = [](auto x) {
return [=](auto y) {
return x+y;
};
};
addf(5)(4) // 9
Write a function swap that swaps the
arguments of a binary function
swap(sub)(3, 2) // -1
auto sub = [](auto x, auto y) {
return x–y;
};
auto swap =[](auto binary) {
return [=](auto x, auto y) {
return binary(y, x);
};
};
swap(sub)(3, 2) // -1
Write a function twice that takes a
binary function and returns a unary
function that passes its argument to
the binary function twice.
twice(add)(11) // 22
auto twice =[](auto binary) {
return [=](auto x) {
return binary(x, x);
};
};
twice(add)(11) // 22
Write a function that takes a binary
function and makes it callable with two
invocations
applyf(mul)(3)(4) // 12
auto applyf = [](auto binary) {
return [binary](auto x) {
return [binary,x](auto y) {
return binary(x, y);
};
};
};
auto a = applyf(mul);
auto b = a(3);
auto c = b(4) // 12
Write a function that takes a function
and an argument and returns a
function that takes the second
argument and applies the function
curry(mul, 3)(4) // 12
auto curry = [](auto binary, auto x) {
return [=](auto y) {
return binary(x, y);
};
};
curry(mul, 3)(4) // 12
» Currying is the technique of transforming a
function that takes multiple arguments in such
a way that it can be called as a chain of
functions, each with a single argument.
» In lambda calculus functions take a single
argument only.
» Must know Currying to understand Haskell
» Currying != Partial function application
auto addFour = [](auto a, auto b,
auto c, auto d) {
return a+b+c+d;
};
auto partial = [](auto func, auto a,
auto b) {
return [=](auto c, auto d) {
return func(a, b, c, d);
};
};
partial(addFour,1,2)(3,4); //10
Without creating a new function show
3 ways to create the inc function
inc(4) // 5
auto inc = curry(add, 1);
auto inc = addf(1);
auto inc = applyf(add)(1);
inc(4) // 5
Write a function composeu that takes
two unary functions and returns a
unary function that calls them both
composeu(inc, curry(mul, 5))(3) // 20
auto composeu =[](auto f1, auto f2) {
return [=](auto x) {
return f2(f1(x));
};
};
composeu(inc1, curry(mul, 5))(3) // 20
Write a function that returns a function
that allows a binary function to be
called exactly once
once(add)(3, 4) // 7
once(add)(3, 4) // error
auto once = [](auto binary) {
bool done = false;
return [=](auto x, auto y) mutable {
if(!done) {
done = true;
return binary(x, y);
}
else
throw std::runtime_error("once!");
};
};
once(add)(3, 4) // 7
once(add)(3, 4) // exception
Write a function that takes a binary
function and returns a function that
takes two arguments and a callback
and invokes the callback on the result
of the binary function.
auto binaryc = [](auto binary) {
return [=](auto x, auto y, auto callbk) {
return callbk(binary(x,y));
};
};
binaryc(mul)(5, 6, inc) // 31
binaryc(mul)(5,6,[](int a) { return a+1; });
Write 3 functions
1. unit – same as Identityf
2. stringify – that stringifies its
argument and applies unit to it
3. bind – that takes a result of unit
and returns a function that takes a
callback and returns the result of
callback applied to the result of
unit.
auto unit = [](auto x) {
return [=]() { return x; };
};
auto stringify = [](auto x) {
std::stringstream ss;
ss << x;
return unit(ss.str());
};
auto bind = [](auto u) {
return [=](auto callback) {
return callback(u());
};
};
std::cout << "Left Identity "
<< stringify(15)()
<< "=="
<< bind(unit(15))(stringify)()
<< std::endl;
std::cout << "Right Identity "
<< stringify(5)()
<< "=="
<< bind(stringify(5))(unit)()
<< std::endl;
Verify
Fun with Lambdas: C++14 Style (part 1)

Contenu connexe

Tendances

11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in cyazad dumasia
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C ProgrammingAnil Pokhrel
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Sanjit Shaw
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract classAmit Trivedi
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarSivakumar R D .
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlinvriddhigupta
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdfchoconyeuquy
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 

Tendances (20)

11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
Managing input and output operation in c
Managing input and output operation in cManaging input and output operation in c
Managing input and output operation in c
 
Function in C Programming
Function in C ProgrammingFunction in C Programming
Function in C Programming
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Polymorphism in c++(ppt)
Polymorphism in c++(ppt)Polymorphism in c++(ppt)
Polymorphism in c++(ppt)
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
Pure virtual function and abstract class
Pure virtual function and abstract classPure virtual function and abstract class
Pure virtual function and abstract class
 
Structure of C++ - R.D.Sivakumar
Structure of C++ - R.D.SivakumarStructure of C++ - R.D.Sivakumar
Structure of C++ - R.D.Sivakumar
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Function in c
Function in cFunction in c
Function in c
 
Features of Java.pptx
Features of Java.pptxFeatures of Java.pptx
Features of Java.pptx
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Python Modules
Python ModulesPython Modules
Python Modules
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 

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

Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Sumant Tambe
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowKrzysztof Szafranek
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchainedEduard Tomàs
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8Omar Bashir
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervosoLuis Vendrame
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docxrafbolet0
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxJohnRehldeGracia
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is hereSebastiano Armeli
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6WebF
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойSigma Software
 
Functional Programming with Javascript
Functional Programming with JavascriptFunctional Programming with Javascript
Functional Programming with JavascriptDeepankar Chopra
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)Domenic Denicola
 

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

Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. NowESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Functional Programming in Java 8
Functional Programming in Java 8Functional Programming in Java 8
Functional Programming in Java 8
 
JavaScript - Agora nervoso
JavaScript - Agora nervosoJavaScript - Agora nervoso
JavaScript - Agora nervoso
 
C++20 features
C++20 features C++20 features
C++20 features
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docxSpring 2014 CSCI 111 Final exam   of 1 61. (2 points) Fl.docx
Spring 2014 CSCI 111 Final exam of 1 61. (2 points) Fl.docx
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Computer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptxComputer-programming-User-defined-function-1.pptx
Computer-programming-User-defined-function-1.pptx
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
ECMAScript 6
ECMAScript 6ECMAScript 6
ECMAScript 6
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Столпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай МозговойСтолпы функционального программирования для адептов ООП, Николай Мозговой
Столпы функционального программирования для адептов ООП, Николай Мозговой
 
Functional Programming with Javascript
Functional Programming with JavascriptFunctional Programming with Javascript
Functional Programming with Javascript
 
The State of JavaScript (2015)
The State of JavaScript (2015)The State of JavaScript (2015)
The State of JavaScript (2015)
 
functions
functionsfunctions
functions
 

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
 
Systematic Generation Data and Types in C++
Systematic Generation Data and Types in C++Systematic Generation Data and Types in C++
Systematic Generation Data and Types in C++Sumant 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
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based TestingSumant 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
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 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 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 (20)

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
 
Systematic Generation Data and Types in C++
Systematic Generation Data and Types in C++Systematic Generation Data and Types in C++
Systematic Generation Data and Types in C++
 
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
 
C++ Generators and Property-based Testing
C++ Generators and Property-based TestingC++ Generators and Property-based Testing
C++ Generators and Property-based Testing
 
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
 
C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012 C++11 Idioms @ Silicon Valley Code Camp 2012
C++11 Idioms @ Silicon Valley Code Camp 2012
 
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

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 

Dernier (20)

Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 

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

  • 1. Sumant Tambe, Ph.D. Microsoft Visual C++ MVP Senior Software Research Engineer Real-Time Innovations, Inc. @sutambe SFBay Association of C/C++ Users March 12, 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. Thanks to Douglas Crockford. Link to Doug’s JavaScript talk
  • 11.
  • 12. Write an Identity function that takes an argument and returns the same argument. Identity(3) //3
  • 13. auto Identity = [](auto x) { return x; };
  • 14. Write 3 functions add, sub, and mul that take 2 parameters each and return their sum, difference, and product respectively. add(3, 4) // 7 sub(4, 3) // 1 mul(4, 5) // 20
  • 15. auto add = [](auto x, auto y) { return x + y; }; auto sub = [](auto x, auto y) { return x - y; }; int mul (int x, int y) { return x * y; };
  • 16. Write a function, identityf, that takes an argument and returns a callable that returns that argument auto idf = identityf(5); idf() // 5
  • 17. auto identityf = [](auto x) { class Inner { int x; public: Inner(int i): x(i) {} int operator() () { return x; } }; return Inner(x); }; auto idf = identityf(5); idf() // 5
  • 18. auto identityf = [](auto x) { return [](){ /* must remember x */ }; };
  • 19. auto identityf = [](auto x) { return [=]() { return x; }; }; auto idf = identityf(5); idf() // 5
  • 20. » A lambda is just an anonymous function. » A closure is a function which closes over the environment in which it was defined. » Not all closures are lambdas and not all lambdas are closures. » Closures are just function objects in C++ » C++ closures do not extend the lifetime of their context. (If you need this use shared_ptr)
  • 21. Write a function that produces a function that returns values in a range fromto(0, 10)
  • 22. auto fromto = [](auto start, auto finish) { return }; auto range = fromto(0, 10) range() // 0 range() // 1 [=]() mutable { if(start < finish) return start++; else throw std::runtime_error(“Complete"); };
  • 23. Write a function that adds from two invocations addf(5)(4) // 9
  • 24. auto addf = [](auto x) { return [=](auto y) { return x+y; }; }; addf(5)(4) // 9
  • 25. Write a function swap that swaps the arguments of a binary function swap(sub)(3, 2) // -1
  • 26. auto sub = [](auto x, auto y) { return x–y; }; auto swap =[](auto binary) { return [=](auto x, auto y) { return binary(y, x); }; }; swap(sub)(3, 2) // -1
  • 27. Write a function twice that takes a binary function and returns a unary function that passes its argument to the binary function twice. twice(add)(11) // 22
  • 28. auto twice =[](auto binary) { return [=](auto x) { return binary(x, x); }; }; twice(add)(11) // 22
  • 29. Write a function that takes a binary function and makes it callable with two invocations applyf(mul)(3)(4) // 12
  • 30. auto applyf = [](auto binary) { return [binary](auto x) { return [binary,x](auto y) { return binary(x, y); }; }; }; auto a = applyf(mul); auto b = a(3); auto c = b(4) // 12
  • 31. Write a function that takes a function and an argument and returns a function that takes the second argument and applies the function curry(mul, 3)(4) // 12
  • 32. auto curry = [](auto binary, auto x) { return [=](auto y) { return binary(x, y); }; }; curry(mul, 3)(4) // 12
  • 33. » Currying is the technique of transforming a function that takes multiple arguments in such a way that it can be called as a chain of functions, each with a single argument. » In lambda calculus functions take a single argument only. » Must know Currying to understand Haskell » Currying != Partial function application
  • 34. auto addFour = [](auto a, auto b, auto c, auto d) { return a+b+c+d; }; auto partial = [](auto func, auto a, auto b) { return [=](auto c, auto d) { return func(a, b, c, d); }; }; partial(addFour,1,2)(3,4); //10
  • 35. Without creating a new function show 3 ways to create the inc function inc(4) // 5
  • 36. auto inc = curry(add, 1); auto inc = addf(1); auto inc = applyf(add)(1); inc(4) // 5
  • 37. Write a function composeu that takes two unary functions and returns a unary function that calls them both composeu(inc, curry(mul, 5))(3) // 20
  • 38. auto composeu =[](auto f1, auto f2) { return [=](auto x) { return f2(f1(x)); }; }; composeu(inc1, curry(mul, 5))(3) // 20
  • 39. Write a function that returns a function that allows a binary function to be called exactly once once(add)(3, 4) // 7 once(add)(3, 4) // error
  • 40. auto once = [](auto binary) { bool done = false; return [=](auto x, auto y) mutable { if(!done) { done = true; return binary(x, y); } else throw std::runtime_error("once!"); }; }; once(add)(3, 4) // 7 once(add)(3, 4) // exception
  • 41. Write a function that takes a binary function and returns a function that takes two arguments and a callback and invokes the callback on the result of the binary function.
  • 42. auto binaryc = [](auto binary) { return [=](auto x, auto y, auto callbk) { return callbk(binary(x,y)); }; }; binaryc(mul)(5, 6, inc) // 31 binaryc(mul)(5,6,[](int a) { return a+1; });
  • 43. Write 3 functions 1. unit – same as Identityf 2. stringify – that stringifies its argument and applies unit to it 3. bind – that takes a result of unit and returns a function that takes a callback and returns the result of callback applied to the result of unit.
  • 44. auto unit = [](auto x) { return [=]() { return x; }; }; auto stringify = [](auto x) { std::stringstream ss; ss << x; return unit(ss.str()); }; auto bind = [](auto u) { return [=](auto callback) { return callback(u()); }; };
  • 45. std::cout << "Left Identity " << stringify(15)() << "==" << bind(unit(15))(stringify)() << std::endl; std::cout << "Right Identity " << stringify(5)() << "==" << bind(stringify(5))(unit)() << std::endl; Verify