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
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
Fun with Lambdas: C++14 Style (part 1)
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)

More Related Content

PDF
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
PDF
Modern c++ (C++ 11/14)
Geeks Anonymes
 
PDF
Monadic Java
Mario Fusco
 
PDF
The Power of Composition (NDC Oslo 2020)
Scott Wlaschin
 
PPTX
Introduction to Rust language programming
Rodolfo Finochietti
 
PDF
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PDF
Introduction to Go programming language
Slawomir Dorzak
 
PDF
Solid C++ by Example
Olve Maudal
 
TypeScript: coding JavaScript without the pain
Sander Mak (@Sander_Mak)
 
Modern c++ (C++ 11/14)
Geeks Anonymes
 
Monadic Java
Mario Fusco
 
The Power of Composition (NDC Oslo 2020)
Scott Wlaschin
 
Introduction to Rust language programming
Rodolfo Finochietti
 
JavaScript: Variables and Functions
Jussi Pohjolainen
 
Introduction to Go programming language
Slawomir Dorzak
 
Solid C++ by Example
Olve Maudal
 

What's hot (20)

PDF
Functional programming
ijcd
 
PPT
Rust Programming Language
Jaeju Kim
 
PPTX
Go Programming Language (Golang)
Ishin Vin
 
PDF
Insecure coding in C (and C++)
Olve Maudal
 
PPTX
純粋関数型アルゴリズム入門
Kimikazu Kato
 
PDF
Idiomatic Kotlin
intelliyole
 
PPT
OOP in C++
ppd1961
 
PPTX
Function in c
Raj Tandukar
 
PPTX
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
PDF
C++11 & C++14
CyberPlusIndia
 
PPTX
C function presentation
Touhidul Shawan
 
PPTX
Functions in c++
Rokonuzzaman Rony
 
PPTX
Capabilities for Resources and Effects
Martin Odersky
 
PPT
Advanced Programming C++
guestf0562b
 
PDF
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
 
PDF
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
PDF
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
PDF
Data Structure in C Programming Language
Arkadeep Dey
 
PDF
OS scheduling and The anatomy of a context switch
Daniel Ben-Zvi
 
Functional programming
ijcd
 
Rust Programming Language
Jaeju Kim
 
Go Programming Language (Golang)
Ishin Vin
 
Insecure coding in C (and C++)
Olve Maudal
 
純粋関数型アルゴリズム入門
Kimikazu Kato
 
Idiomatic Kotlin
intelliyole
 
OOP in C++
ppd1961
 
Function in c
Raj Tandukar
 
USE OF PRINT IN PYTHON PART 2
vikram mahendra
 
C++11 & C++14
CyberPlusIndia
 
C function presentation
Touhidul Shawan
 
Functions in c++
Rokonuzzaman Rony
 
Capabilities for Resources and Effects
Martin Odersky
 
Advanced Programming C++
guestf0562b
 
Writing Parsers and Compilers with PLY
David Beazley (Dabeaz LLC)
 
Domain Driven Design with the F# type System -- NDC London 2013
Scott Wlaschin
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
Data Structure in C Programming Language
Arkadeep Dey
 
OS scheduling and The anatomy of a context switch
Daniel Ben-Zvi
 
Ad

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

PPTX
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
PDF
Thinking in Functions
Alexandru Bolboaca
 
PDF
Programming fundamentals using c++ question paper 2014 tutorialsduniya
TutorialsDuniya.com
 
PDF
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
PDF
Functional programming java
Maneesh Chaturvedi
 
PDF
The present and the future of functional programming in c++
Alexander Granin
 
PDF
Data Structure and Algorithm
PRIYA DARSHINI A/P VEJAN
 
PPTX
The Style of C++ 11
Sasha Goldshtein
 
PDF
The Present and The Future of Functional Programming in C++
Alexander Granin
 
PDF
Functional programming in C++
Alexandru Bolboaca
 
PPT
Lecture#6 functions in c++
NUST Stuff
 
PDF
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
PDF
Generic programming and concepts that should be in C++
Anton Kolotaev
 
PPT
Chap 5 c++
Venkateswarlu Vuggam
 
PDF
Chap 5 c++
Venkateswarlu Vuggam
 
PPT
Cpphtp4 ppt 03
sanya6900
 
PPT
cpphtp4_PPT_03.ppt
Suleman Khan
 
PPTX
Functions in C++
home
 
PDF
Solutions for Exercises – Data Structures and Algorithms in C++ (2nd Edition)...
maryarchitect25
 
PPTX
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Fun with Lambdas: C++14 Style (part 2)
Sumant Tambe
 
Thinking in Functions
Alexandru Bolboaca
 
Programming fundamentals using c++ question paper 2014 tutorialsduniya
TutorialsDuniya.com
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
Ovidiu Farauanu
 
Functional programming java
Maneesh Chaturvedi
 
The present and the future of functional programming in c++
Alexander Granin
 
Data Structure and Algorithm
PRIYA DARSHINI A/P VEJAN
 
The Style of C++ 11
Sasha Goldshtein
 
The Present and The Future of Functional Programming in C++
Alexander Granin
 
Functional programming in C++
Alexandru Bolboaca
 
Lecture#6 functions in c++
NUST Stuff
 
C++ normal assignments by maharshi_jd.pdf
maharshi1731
 
Generic programming and concepts that should be in C++
Anton Kolotaev
 
Cpphtp4 ppt 03
sanya6900
 
cpphtp4_PPT_03.ppt
Suleman Khan
 
Functions in C++
home
 
Solutions for Exercises – Data Structures and Algorithms in C++ (2nd Edition)...
maryarchitect25
 
6. Functions in C ++ programming object oriented programming
Ahmad177077
 
Ad

More from Sumant Tambe (20)

PDF
Kafka tiered-storage-meetup-2022-final-presented
Sumant Tambe
 
PPTX
Systematic Generation Data and Types in C++
Sumant Tambe
 
PPTX
Tuning kafka pipelines
Sumant Tambe
 
PPTX
New Tools for a More Functional C++
Sumant Tambe
 
PPTX
C++ Coroutines
Sumant Tambe
 
PPTX
C++ Generators and Property-based Testing
Sumant Tambe
 
PDF
Reactive Stream Processing in Industrial IoT using DDS and Rx
Sumant Tambe
 
PDF
RPC over DDS Beta 1
Sumant Tambe
 
PDF
Remote Log Analytics Using DDS, ELK, and RxJS
Sumant Tambe
 
PDF
Property-based Testing and Generators (Lua)
Sumant Tambe
 
PDF
Reactive Stream Processing for Data-centric Publish/Subscribe
Sumant Tambe
 
PDF
Reactive Stream Processing Using DDS and Rx
Sumant Tambe
 
PDF
An Extensible Architecture for Avionics Sensor Health Assessment Using DDS
Sumant Tambe
 
PDF
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Sumant Tambe
 
PDF
Standardizing the Data Distribution Service (DDS) API for Modern C++
Sumant Tambe
 
PDF
Communication Patterns Using Data-Centric Publish/Subscribe
Sumant Tambe
 
PDF
C++11 Idioms @ Silicon Valley Code Camp 2012
Sumant Tambe
 
PPTX
Retargeting Embedded Software Stack for Many-Core Systems
Sumant Tambe
 
PPTX
Ph.D. Dissertation
Sumant Tambe
 
PDF
Native XML processing in C++ (BoostCon'11)
Sumant Tambe
 
Kafka tiered-storage-meetup-2022-final-presented
Sumant Tambe
 
Systematic Generation Data and Types in C++
Sumant Tambe
 
Tuning kafka pipelines
Sumant Tambe
 
New Tools for a More Functional C++
Sumant Tambe
 
C++ Coroutines
Sumant Tambe
 
C++ Generators and Property-based Testing
Sumant Tambe
 
Reactive Stream Processing in Industrial IoT using DDS and Rx
Sumant Tambe
 
RPC over DDS Beta 1
Sumant Tambe
 
Remote Log Analytics Using DDS, ELK, and RxJS
Sumant Tambe
 
Property-based Testing and Generators (Lua)
Sumant Tambe
 
Reactive Stream Processing for Data-centric Publish/Subscribe
Sumant Tambe
 
Reactive Stream Processing Using DDS and Rx
Sumant Tambe
 
An Extensible Architecture for Avionics Sensor Health Assessment Using DDS
Sumant Tambe
 
Overloading in Overdrive: A Generic Data-Centric Messaging Library for DDS
Sumant Tambe
 
Standardizing the Data Distribution Service (DDS) API for Modern C++
Sumant Tambe
 
Communication Patterns Using Data-Centric Publish/Subscribe
Sumant Tambe
 
C++11 Idioms @ Silicon Valley Code Camp 2012
Sumant Tambe
 
Retargeting Embedded Software Stack for Many-Core Systems
Sumant Tambe
 
Ph.D. Dissertation
Sumant Tambe
 
Native XML processing in C++ (BoostCon'11)
Sumant Tambe
 

Recently uploaded (20)

PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Agile Chennai 18-19 July 2025 | Emerging patterns in Agentic AI by Bharani Su...
AgileNetwork
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
AI in Daily Life: How Artificial Intelligence Helps Us Every Day
vanshrpatil7
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 

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
  • 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