Skip to content

GrantMoyer/lambda_hpp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

λ.hpp is a syntatic sugar, dubbed λ expressions, for C++20 lambdas. The syntax is reminicent of Scala's placeholder syntax, but not identical.

Example usage

λ expressions can be used in most places a lambda can be used.

λ expressions can use _1, _2, _3, and _4 as implicitly defined positional arguments.

array arr{8, 5, 4, 2, 9, 6, 7, 3, 1};
ranges::sort(arr, λ(_1 > _2));

9, 8, 7, 6, 5, 4, 3, 2, 1

For convenience "_" may be used as an alias for "_1".

auto e = *ranges::find_if(arr, λ(_ < 4));

3

Trying to use an unexpected parameter results in a compile error.

ranges::find_if(arr, λ(_2 < 4)); // illegal
error: invalid operands to binary expression ('λ::unassigned' and 'int')
    ranges::find_if(arr, λ(_2 < 4)); // illegal
                           ~~ ^ ~

λ expressions implicitly capture variables by reference.

auto m = 3;
auto n = ranges::count_if(arr, λ(_ % m == 0));

3

Not all available parameters need to be used in a λ expression.

ranges::transform(arr, arr.data(), λ(0));

0, 0, 0, 0, 0, 0, 0, 0, 0

Methods on λ expression parameters can be called like normal.

array<string, 9> arr2{};
char c = 'a';
ranges::for_each(arr2, λ(_.push_back(c++)));

a, b, c, d, e, f, g, h, i

It's even possible to store a λ expression to an intermediate variable.

auto join_with_dash = λ(_1 + '-' + _2);
auto s = reduce(arr2.begin() + 1, arr2.end(), arr2[0], join_with_dash);

a-b-c-d-e-f-g-h-i

About

A simple-to-use, horrifying-to-reason-about syntatic sugar for C++20 lambdas

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages