r/cpp • u/fredoverflow • May 10 '22
Is short lambda syntax on the C++ radar?
Mom, can we get x=>x+1 ?
No, we have x=>x+1 at home.
x=>x+1 at home:
[](const auto& x) { return x + 1; }
61
u/dgkimpton May 10 '22
Even a half way house like [](const &x) => x+1 would be nicer. Trouble is, C++ parsing is already a nightmare and all these sugars just make it harder, so I'm not holding out much hope.
-5
u/fly2never May 11 '22
use std as_const
13
u/dgkimpton May 11 '22
I'm not sure how
std::as_constis going to help reduce the signature complexity of a lambda... care to expand on that cryptic statement a bit?
118
u/gracicot May 10 '22
You mean [](auto const& x) noexcept(noexcept(x + 1)) -> decltype(x + 1) { return x + 1; } right?
41
23
20
1
u/TheOmegaCarrot May 16 '22
TIL you can slap
noexcepton a lambda.What’s with the doubling up though?
2
u/gracicot May 16 '22
The outer
noexceptis the noexcept specifier. You can send in a boolean to either put noexcept to true or noexcept to false. For example,[](int a) noexcept(true) {}is noexcept, and[](int a) noexcept(false) {}is not noexcept.The inner noexcept is the noexcept operator. You send in an expression, and it returns if an expression is noexcept or not.
So in all, is sets the noexcept-ness of the lambda to the noexcept-ness of the expression
x + 1.1
1
-22
u/RishabhRD May 10 '22
I wish someday C++ commitee would remove exceptions from language..... There can be some fatal error mechanism but exceptions are really bad
15
u/KingAggressive1498 May 11 '22
Unwinding the stack and executing destructors is desirable "recoverable critical error" behavior for many types of application, and even desirable "unrecoverable error" for GUI applications, but requires considerable care (and extra runtime cost) to keep global (or even just broader scope) state from being corrupted and other threads from seeing and acting upon intermediate states.
Basically, in many code bases recovering safely and reliably from an exception requires an aggressive embrace of transactional programming models rarely seen outside of specific contexts (ie databases) but that's ultimately a failing of developers rather than the feature.
Switching to the C pattern of returning error codes until the program can continue normally or make a decision to terminate does not resolve that problem either btw. It's really a fundamental problem of error recovery.
Ofc C++ exceptions aren't the perfect error handling abstraction. But the biggest thing they justly get flak for is violating the "don't pay for what you don't use" principle (essentially, the STL and other exception throwing libraries should have an obvious way to make all its objects and functions noexcept for code that isn't even trying to handle exceptions, and since it doesn't that type of code still has to pay the fixed costs of having exception handling).
1
u/RishabhRD May 11 '22
I am that monad person.... I prefer std::expected(C++23) for exceptions.... Like rust and haskell. std::expected has similar behavior as stack unwinding right? At any point any function returns error calling function's monadic bjnd would not continue and calling function would breturn error too and this behavior continues potentially till main.
1
u/KingAggressive1498 May 11 '22
With
expectedyou'll pay less for what you don't use (in the case that you don't care about errors) but at the cost of slightly more time spent on boilerplate.FWIW I prefer the idea of a monadic return type over having to always pass an std::error_code by reference for dealing with non-critical errors anyway. I don't know if it's faster, but an unexpected exception for a predictable minor error because I forgot in one place is not particularly fun (especially in a noexcept call path), and that's my biggest beef with filesystem and asio (at least since asio finally added portable support for random access file I/O last year)
3
u/RishabhRD May 11 '22
Regarding boilerplate I find it better than noexcept(noexcept(....)). And I like the fact that possible errors are explicitly mentioned in return type. Maybe its just matter of taste
4
u/goranlepuz May 11 '22
I like the fact that possible errors are explicitly mentioned in return type.
Authors of Java did that. After some years and an underwhelming experience, some major Java libraries just eschew checked exceand go for runtime ones.
The underlying reason for that, I think is quite obvious: for a sufficiently complex program (or even one function with sufficient functionality underneath it), knowing all failure modes is not necessary or even practical. For most of failure modes, what we care about is how to report errors.
Having errors mentioned in return type, therefore, goes against the common case of just letting the error propagate and does not help with reporting the error any more than exceptions do.
1
u/RishabhRD May 11 '22
I agree with your concern. I am not sure about the right way.... But we always can have a type erased wrapper for errors when we don't care about them. However that leads to unnecessary memory allocation. We can use auto return type for single control flow.... However functions having multiple ways to return would need to use sum type of all possible error types. This type algebra may need more boilerplate... I don't know if we can reduce it. Maybe not... I am still exploring over it.... Bcz in my head currently i think vector allocation exception is a good example... We don't want to handle this till main function many times. The simple way to know if there exist a solution is to look at rust maybe... I would do that and comment here
2
u/jk-jeon May 11 '22
If you think about it, exception works just like monads. It just does it implicitly, for legitimate reasons.
1
u/RishabhRD May 11 '22
Actually yes I realised that my argument that exceptions should be removed is bad. I went through many error handling mechanisms today. And I feel unrecoverable error should be thrown as exceptions and recoverable error should be returned as std::expected. Like vector out of bounds is a non recoverable error and continuing the program after this doesn't make sense. And hence stack unwinding should be done and program should be aborted.
However file not found is recoverable and error should be returned wrapped in std::expected. This approach is similar to rust and haskell error handling.
→ More replies (0)1
u/KingAggressive1498 May 11 '22
Hmm. Especially since operator noexcept requires an expression, you might be right that it's actually not more boilerplate (or at least simpler boilerplate)
1
u/teerre May 11 '22
Boilerplate (which in C++ is a curious worry) is only relevant if the implemention is superficial. The languages the other user mentioned have many mechanisms to descend and ascend types. Using those mechanisms verbosity is largely avoided.
1
u/KingAggressive1498 May 11 '22
The additions of
auto,decltype, and lambdas in C++11 were primarily useful because they reduced boilerplate. I can't be the only one who uses boost's config.hpp even when I'm not using a single other feature from boost to minimize the time I spend writing boilerplate to deal with different compilers and platforms.So sure, C++ generally just requires that you write a lot of boilerplate, but it's not like it's a non-concern for either developers or the standards committee.
I'm not 100% sure what you mean by ascending and descending types, but the boilerplate is not from the return type. It's from dealing with the error return condition in intermediate functions. With exceptions, the error gets passed forward with no additional code. With
expectedyou'll wind up with code like:expected<T,E> eret = internal_call(...args); if(!eret) return eret; T result = eret.value(); // do some work with result return result;In the case that
internal_callis the last thing for the function to do, and the expected T are the same type, there's no additional boilerplate and you can just directly forward the return value.1
u/teerre May 11 '22
I'm talking about ascending base types to result types and vice-versa, similar to what happens to containers. Facilities like
and_then,map,or_elseetc. avoid precisely this kind of code.1
u/KingAggressive1498 May 11 '22
Yes, this boilerplate can easily be reduced in existing C++ with some helper macros (this is basically the method used by boost.LEAF but I didn't really look at that much). Still more boilerplate than exceptions even if it becomes a syntactically cleaner C++ language feature.
48
u/Mrkol May 11 '22
Nah, x=>x+1 at home is actually[](const auto&& x) noexcept(noexcept(operator+(forward<decltype(x)>(x), 1))) requires requires { operator+(forward<decltype(x)>(x), 1); } -> decltype(auto) { return operator+(forward<decltype(x)>(x), 1); }
14
20
12
4
u/phoeen May 12 '22
x is not a forwarding reference because you add const to its auto&& declaration. so all this forwarding stuff is "wrong" :-P
1
14
u/bikki420 May 11 '22 edited May 11 '22
#define λ []( [[maybe_unused]] auto &&x )
#include <fmt/core.h>
#include <ranges>
#include <algorithm>
int main() {
using namespace std::ranges;
for_each( views::iota(0)
| views::take(10)
| views::filter( λ { return x % 2 == 0; } ),
λ { fmt::print("{} ", x); } ); // >> 0 2 4 6 8
}Single argument restriction + still got to type out the return though.
edit-1:
I suppose another option would be something like this to avoid the return:
#define λ(EXPR) []( [[maybe_unused]] auto &&x ) noexcept(noexcept(EXPR)) -> decltype(EXPR) { return (EXPR); }
#include <fmt/core.h>
#include <ranges>
#include <algorithm>
int main() {
using namespace std::ranges;
for_each( views::iota(0)
| views::take(10)
| views::filter( λ( x % 2 == 0 ) ),
λ( fmt::print("{} ", x) ) ); // 0 2 4 6 8
}edit-2:
And something like this to allow for other arities:
#define λARG [[maybe_unused]] auto &&
#define λBODY(EXPR) noexcept(noexcept(EXPR)) -> decltype(EXPR) { return (EXPR); }
#define λ0(EXPR) []() λBODY(EXPR) // nullary
#define λ1(EXPR) []( λARG x ) λBODY(EXPR) // unary
#define λ2(EXPR) []( λARG x, λARG y ) λBODY(EXPR) // binary
#define λ3(EXPR) []( λARG x, λARG y, λARG z ) λBODY(EXPR) // ternary
#define λ4(EXPR) []( λARG x, λARG y, λARG z, λARG w ) λBODY(EXPR) // quaternary
// ...
#define λn(EXPR) []( λARG...args ) λBODY(EXPR) // n-nary (parameter pack)Maybe some more uniform naming scheme for the parameters (e.g. arg1, arg2, arg3, arg4, ... args). Although I personally don't see much benefit in going higher than the arity of λ4 (which is already excessive, IMO) with the exception of the n-nary case. Generally you'd just want the nullary, unary, binary, or the n-nary case, after all.
10
u/nintendiator2 May 11 '22
Thanks I hate it.
Added to personal library!
6
u/bikki420 May 11 '22 edited May 11 '22
Enjoy 🙏
I'd recommend throwing in a
#define FWD(X) std::forward<decltype(X)>(X)too if you plan on using it for any non-primitive types as well. It's a shame there's no viable way to have the macro automatically add it. The only way I can think of would be to have a macro for each argument, but I can't think of any good identifiers for that approach.IMO, it ends up surprisingly nice (apart from the evil macro usage):
auto sqr = λ1( x*x ); auto mul = λ2( x*y ); auto fma = λ3( x*y+z ); auto sum = λn( (FWD(args) + ...) );Ideally the xs, ys, and zs ought to be forwarded too.
vs.
auto sqr = []( auto &&x ) noexcept(noexcept(x*x)) -> decltype(x*x) { return x*x; }; auto mul = []( auto &&x, auto &&y ) noexcept(noexcept(x*y)) -> decltype(x*y) { return x*y; }; auto fma = []( auto &&x, auto &&y, auto &&z ) noexcept(noexcept(x*y+z)) -> decltype(x*y+z) { return x*y+z; }; auto sum = []( auto &&...args ) noexcept(noexcept((std::forward<decltype(args)>(args) + ...))) -> decltype((std::forward<decltype(args)>(args) + ...)) { return (std::forward<decltype(args)>(args) + ...); };Also, another comment suggested using names like
λx,λxy,λxyz, etc instead.edit:
I'm not sure how valid it is to use
$in macro identifiers, but since we're committed to evil already, one option might be to imitate shell scripts:#define FWD(X) std::forward<decltype(X)>(X) #define λARG_T [[maybe_unused]] auto && #define λBODY(EXPR) noexcept(noexcept(EXPR)) -> decltype(EXPR) { return (EXPR); } #define λ0(EXPR) []() λBODY(EXPR) // nullary #define λ1(EXPR) []( λARG_T arg1 ) λBODY(EXPR) // unary #define λ2(EXPR) []( λARG_T arg1, λARG_T arg2 ) λBODY(EXPR) // binary #define λ3(EXPR) []( λARG_T arg1, λARG_T arg2, λARG_T arg3 ) λBODY(EXPR) // ternary #define λ4(EXPR) []( λARG_T arg1, λARG_T arg2, λARG_T arg3, λARG_T arg4 ) λBODY(EXPR) // quaternary // ... // ... #define λn(EXPR) []( λARG_T...args ) λBODY(EXPR) // n-nary #define $1 FWD(arg1) #define $2 FWD(arg2) #define $3 FWD(arg3) #define $4 FWD(arg4) // ... #define $args FWD(args)In which case it would look like:
auto sqr = λ1( $1 * $1 ); auto mul = λ2( $1 * $2 ); auto fma = λ3( $1 * $2 + $3 ); auto sum = λn( ($args + ...) );edit:
It seems like gcc doesn't complain about the
$, but Clang complains unless you silence it with-Wno-dollar-in-identifier-extension. No idea about MSVC.5
u/nintendiator2 May 11 '22
Your evil so far is quite funny and I just can't stop appreciating that you manage to throw in all of Unicode, macros, std daisychaining, noexcept madness and unused ASCII glyphs into a monstrosity that makes writing decent C++ much, much easier than all the people who abhor those little things you threw in, in particular macros, and then they throw a fit over it.
If macros have their place, this is it.
2
u/Nobody_1707 May 11 '22
Swift also uses $n for unnamed closure arguments, but it starts counting from 0. Certainly doesn't seem a bad idea since you've got C levels of macro use anyway.
2
u/Nobody_1707 May 11 '22 edited May 11 '22
If we had P1858 we could do this:
#define FWD(X) std::forward<decltype(X)>(X) #define λARG_T [[maybe_unused]] auto && #define λBODY(EXPR) noexcept(noexcept(EXPR)) -> decltype(EXPR) { return (EXPR); } #define λ(EXPR) []( λARG_T...λargs ) λBODY(EXPR) #define $0 FWD(λargs...[0]) #define $1 FWD(λargs...[1]) #define $2 FWD(λargs...[2]) #define $3 FWD(λargs...[3]) #define $n(N) FWD(λargs...[N])
Which would be a lot simpler. Sadly, I don't think that paper is going to be accepted any time soon.
1
u/bikki420 May 12 '22
Oh, that would've been nice.
Also, I realized that it might be wise to remove the capture list from the
#define λ0(EXPR) ...lines to allow for capturing like:int counter = 0; auto increment_counter = [&counter] λ0(++counter);Although the usefulness is a bit limited though since EXPR can't really contain more complex behaviour like control flow stuff.
8
May 11 '22
Instead λ3 an identifier like λxyz is closer to the lambda notation and makes easier to remember parameter names.
3
2
u/Nobody_1707 May 11 '22
Seeing as how the return statement is the only evalutated use of
EXPR, wouldn't it be better not to parenthesize it so that the user can decide whether to return a value or a reference?1
u/Nobody_1707 May 11 '22
Actually, I think the fact that it isn't parenthesized in
decltpe(EXPR)already does that, but it wasn't obvious to me at first glance.1
u/bikki420 May 11 '22
Hmm, sorry, I'm not quite sure I'm following the parenthesis' role in that, mind elaborating how the two would differ? (E.g. on the callsite or whatever)
I took your advice and switched to zero indexing, here's the current version. Thanks for the suggestions. 🙏
2
u/Nobody_1707 May 12 '22
I had a brain fart. I was thinking that
(expr)produced an lvalue reference, but that's only true for(identifier).2
2
Jun 14 '22
In C++20 you could use template lambdas with defaulted template types + defaulted parameters to use a single macro, right?
#define λBODY(EXPR) noexcept(noexcept(EXPR)) -> decltype(EXPR) { return (EXPR); } #define λ(EXPR) []<typename T0 = int, typename T1 = int, typename T2 = int> \ ([[maybe_unused]] T0&& x = T0{}, [[maybe_unused]] T1&& y = T1{}, [[maybe_unused]] T2&& z = T2{}) λBODY(EXPR)I was unsure on the validity of the default parameter for types that don't have a zero-parameter constructor, but it seems to compile fine on all compilers. I guess it's not evaluated if a parameter is supplied.
21
u/Circlejerker_ May 11 '22
Why? C++ should have a uniform syntax, not a new syntax for every feature. This is how languages grow obscure and unusable in collaborative settings.
9
u/flatulentrobot May 11 '22
Remember the "good old days" of functors? Felt like I stared at more colons than a proctologist.
1
13
u/DessertEagle May 10 '22
Since this is not going to happen in the standard, I use the following macro (yeah, macros are evil, except for those that we write ourselves, because we always have perfectly good reasons, right?)
struct cat_t
{
std::string name;
int age;
};
#define L(expr) ([&](auto&& _ ){ return expr; })
int main()
{
const auto cats = std::vector<cat_t>{{{"Foo", 1}, {"Bar", 2}}};
assert(1 == std::count_if(cats.begin(), cats.end(), L(_.age > 1)));
}32
u/NilacTheGrim May 10 '22
Hmm. L() as a def might conflict with something somewhere. You should use Unicode and do:
#define λ(expr) ([&](auto&& _) { return expr; })And bind
λto a hotkey ... :P5
u/bitsynthesis May 11 '22
oof. there was a time when i worked on data science code which used unicode symbols for variable names. i don't like to think about it.
0
May 11 '22
[deleted]
2
May 11 '22 edited May 11 '22
In Windows you only need this to create your own fancy layout (also creates an installer to deploy it): https://www.microsoft.com/en-us/download/details.aspx?id=102134
I just updated my own to use Ctrl+Alt+L for lower case lambda and works :)3
u/Daguerreo86 May 11 '22
The thing which scares me it's not the macro, rather the unconditional capture al by reference.
2
1
u/nintendiator2 May 11 '22
Any practical way to define the macro in C++11 where lambda auto is not a thing?
8
2
u/GYN-k4H-Q3z-75B May 11 '22
I keep thinking the same. I mostly use C# at work and I've switched to lambda for almost all short functions. It just feels very natural and clean there. In C++, I use lambda but it feels clunky and verbose. Having to write the braces and return should not be necessary. How about [](const auto &x) -> x + 1;? It probably turns out using -> as part of lambda instead of => (like C# does) is a nightmare for the compiler.
2
u/Glittering-Water942 May 11 '22
I like c++'s syntax for lambdas, help keep closures and lambdas tracable.
2
u/mattbas May 12 '22
I think this would not work on most places.
What if I need to specify the type for x? What if I need captures?
There are way more cases where an arrow syntax would not work than cases where it would work...
3
2
u/bziur May 10 '22
now can You explain me what x=>x+1 means? Why would we want such a bizzare thing?
17
u/The_3rd_reader May 10 '22
same way as you would explain what
[](auto x) -> decltype(x) {return x+1;}means, by unrolling syntax sugar1
5
u/flatulentrobot May 11 '22
Because all the cool kids are doing JavaScript so everything needs to look like that
7
3
u/phatlynx May 11 '22
I’ve been doing python for the past few months, it’s just so fun to write lambdas and list comprehensions for small projects.
-11
u/NilacTheGrim May 10 '22
It means what a python dewd would recognize as
lambda x: x + 1because OP is a python dewd i guess...17
u/Ranoiaetep_ May 11 '22
Why do you assume OP is into python when there are multiple other popular languages use the exact syntax, such as C# and JS; and Java uses basically the same syntax, except uses
->instead of=>?
2
u/Voltra_Neo May 10 '22
I'd love that, I assume many would love that, doesn't seem like it gets a lot of love in papers
1
u/Quincunx271 Author of P2404/P2405 May 11 '22
I have a library that adds terse lambdas via a macro: https://github.com/Quincunx271/TerseLambda.
[] TL(_1 + 1) // x => x + 1I would be reluctant to see its use in production code, though I happily use it for my personal projects.
1
u/Pragmatician May 11 '22
Boost.Lambda2 does the same thing but without the macro:
_1 + 1.3
u/Quincunx271 Author of P2404/P2405 May 11 '22
Boost.Lambda2 does NOT do the same thing, because it cannot support arbitrary expressions, e.g. _1.name().
2
u/dodheim May 16 '22
Not arbitrary expressions, but it can use data members and member functions:
_1->*&X::name. (Yes, it's hideous, and that's without throwing overloads into the mix.)
1
0
u/axilmar May 11 '22
I don't see any reason why this is good.
A few c++ programmers being lazy cannot justify the energy required by the committee and the compiler vendors to implement this.
1
u/eyes-are-fading-blue May 12 '22
"Cute" changes are discouraged by the direction group. I am not sure if this falls into that category.
my 2 cents: any alternative proposal that's sole purpose is to save 8 characters shouldn't make it into language.
-10
u/Electronicks22 May 10 '22
If you want to code in python, by all means go ahead. C++ is a strongly typed compiled language, one can't make away with that. In that syntax you propose, is x the functor name, the parameter, or both? How do you declare a short lambda with two parameters? It just wouldn't work.
15
u/sphere991 May 10 '22 edited May 10 '22
There are other statically typed languages that nevertheless have shorter lambdas. Off the top of my head: Scala, Rust, Swift, Java, C#. Probably missing some significant ones too.
In that syntax you propose, is x the functor name, the parameter, or both? How do you declare a short lambda with two parameters? It just wouldn't work.
In
x=>x+1,xwould be the parameter, there would be no name to this function object (it's an anonymous function object). This is exactly the syntax that JavaScript, Scala, and C# use, and nearly the same syntax that Java uses (->instead of=>).Two parameters just is
(x, y) => x + y. It's possible that the parentheses are optional in at least one of those languages but I don't know off the top of my head.12
u/F-J-W May 10 '22
The most important one: Haskell (
(\x -> x+1)).Aka everyone’s poster-child for strongly typed compiled languages with lambdas.
2
u/QuotheFan May 11 '22
Haskell is the dream language for most people to work in. It is less popular in action because one person's dream is another person's nightmare.
11
u/F-J-W May 10 '22
Nothing of this has anything to do with strong typing or being compiled. This is about tons of useless boilerplate that are completely unnecessary and hide what is actually going on. The obvious explanation is that
xis the name of the parameter, it’s type will either beconst auto&orauto&&and the other values in the scope will either be captured by[=]or by[&]. These are two decissions with exactly two sensible options each, easily in the realm where the committee can just make a decission and no matter which one it was, most people would be fine with it.There are hard problems when it comes to language-design. This categorically isn’t one of them.
8
u/NilacTheGrim May 10 '22
I suppose if you go with the python analogy it would be
x, y => x + yor something.. this would be the equivalent of[](auto x, auto y) { return x + y; }And for the record I hate it. I think the current lambda syntax is concise enough. I agree, this isn't Python.
0
May 10 '22
[deleted]
4
u/pandorafalters May 11 '22
C++ is several variably well-designed languages glued together with cruft and historical baggage.
-1
u/Nuxij May 11 '22
JS has stupid issues too though, try returning a JSON object from your lambda and see the curlys double up and add a return!
x => { return {"x": 0} }
8
u/helloiamsomeone May 11 '22
(x) => ({ x })Also, that's not JSON. You would have had to call
JSON.stringifyto turn something into JSON.1
3
May 11 '22
[removed] — view removed comment
6
u/helloiamsomeone May 11 '22
Why would you use another set of curlies when just returning an object only needs parens?
Arrow functions also have semantic differences to regular functions in JS, since they bind the
thisargument in the lexical scope of their creation, so allowing them to have a full body is okay.4
u/MutantSheepdog May 11 '22
I doubt that situation would come up in c++ unless you were having an abbreviated lambda that you actually wanted to return a
std::initializer_list- an in that case I'm sure you could just wrap it in parentheses or go with the current syntax.2
-23
u/DavidDinamit May 10 '22
let's turn the language into a heap of sugar, yeah!(no)
34
u/jcelerier ossia score May 10 '22
this was said for introducing lambdas, auto variables, auto as lambda function argument, shorthand concept syntax and auto function parameters, and every time the sugar ended up making the language strictly better
-2
u/DavidDinamit May 10 '22
auto in function parameters exist just because template lambdas was forbitten, concepts never was just a sugar, auto too.
19
u/stilgarpl May 10 '22 edited May 10 '22
I hate comparison of new features to "sugar". Whole C++ is just a sugar for C.
Short lambdas make the code more readable. See how clean and neat Java Streams with lambdas look, and compare to the same algorithm using C++ ranges with C++ lambdas...
9
u/administratrator May 10 '22
Whole C++ is just a sugar for C
I love this comment. Technically almost every language is syntax sugar for C
6
u/aeropl3b May 10 '22
Not, it is all assembly sugar :p
6
u/NilacTheGrim May 10 '22
No, assembly is just sugar for manually editing the bits in a binary file using a hex editor.
6
u/Som1Lse May 10 '22
And a hex editor is just sugar for manually flipping switches. It is sugar all the way down.
3
8
0
May 10 '22
[deleted]
20
u/JNighthawk gamedev May 11 '22
As someone who acutely remembers having to write structs in anonymous namespaces
I've overloaded many a paranthesis operator back in the day.
73
u/NilacTheGrim May 10 '22
Same here. Kids these days...
38
u/Miguecraft May 10 '22
Life is good, but it can be better
22
May 11 '22
[removed] — view removed comment
10
u/Thick-Pineapple666 May 11 '22 edited May 11 '22
In many ways, you're right, but here we don't have to look at JavaScript. It's also a handy C# feature.
2
May 11 '22
[removed] — view removed comment
6
u/Thick-Pineapple666 May 11 '22
A shorter lambda-return syntax has nothing to do with being garbage collected or not.
3
u/HolyGarbage May 11 '22
Then let's take a page out of Haskell! Beautiful example of functional syntax done right.
10
4
u/MiloDC May 11 '22
"I remember when we had to use our fingers, be glad you have an abacus and quit griping that you don't have a calculator."
God love crusty old fart engineers.
P.S. C++ will finally get short-syntax lambdas in about ten years, in keeping with the language's current rate of modernization relative to other languages.
0
May 11 '22
[deleted]
9
u/pjmlp May 11 '22
When list comprehension gets clever it is easier to switch to usual function calls, and C++20 already offers that.
poop | std::views::transform(foo)8
u/GYN-k4H-Q3z-75B May 11 '22
C++20
Cries in having to support Apple Clang
2
u/pjmlp May 11 '22
Apparently Apple only cares about LLVM, and clang to the extent it helps to implement Metal Shader Language, Objective-C and Swift runtimes.
With them behaving like this, and Google now busy with other stuff, it is up to the remaining compiler vendors to actually improve clang upstream, assuming they like the value of clang's existence.
0
May 10 '22
[deleted]
34
u/disperso May 10 '22
I don't see abbreviated lambdas as something bad (and I do like my syntax sugar with extra sweetener on top), but I have to admit that I had a really hard, hard, hard time at reading some code in modern JS where the abbreviated syntax is used. I had to re-type it with the old style to be able to start understanding it. The explicit return and the braces helped me a lot.
In C++ world, I'm so used to typing lambdas with the full notation that I don't see that as much of a problem. It's true that I need shortcuts to type faster all the braces (which on the Spanish keyboard are a pain), but I need them anyway to type the regular braces for anything else.
If I could ask for some syntax sugar, I would prioritise a breakable scope.
8
u/dgkimpton May 10 '22
Off topic question: what is breakable scope giving you that goto doesn't?
28
13
u/pandorafalters May 11 '22
Nobody's misapplied a critique of a superficially similar feature from a completely different language to it in order to object to any possible use without bothering to understand it.
Yet.
4
u/DessertEagle May 10 '22
do { assert(true); break; assert(false); } while(0); // once1
u/disperso May 11 '22
Exactly! But the macro from that repo supports some more things, and it would be something with a name that people could recognize. A do/while false seems something that some people would reject on code review for being obscure in intention.
1
u/serviscope_minor May 11 '22
In C++ world, I'm so used to typing lambdas with the full notation that I don't see that as much of a problem.
I see where you're coming from but I got so used to > > that I never saw it as a problem and it took several years for >> not to make my skin crawl. Really that's a bit of Stockholm syndrome for you. Now I'm free I'd never go back! >> 4 lyfe!
We certainly can C++ just fine all day without abbreviated lambda syntax, but it's just one of those daily things that makes a fair bit of code a bit nicer. Like range for. Easy enough to write:
for(auto i=begin(container); i != end(container); ++i)but range for is just nice.
33
u/sphere991 May 10 '22 edited May 10 '22
As I see it, the return-type issue isn't an issue at all: just use value semantics. That is what C++ programmers expect to happen by default. If you need to return a reference, fall back to an old-style lambda. Most lambdas return by value, so they should have the better syntax.
Cue the inevitable sea of complaints about how idiotic everyone on the C++ committee is and that C++ is a NIGHTMARE when:
// performs N string copies auto a = std::ranges::min_element(people, {}, p => p.name); // performs 0 string copies auto b = std::ranges::min_element(people, {}, [](auto const& p) -> string const& { return p.name; });It's easy to say that this is what you should expect because of value semantics, but a lot less so when the convenient syntax isn't at all what you want, to the point where you just start avoiding using it.
3
5
u/gracicot May 10 '22
I would love
x => auto(x)for value,x => (x)for reference andx => xfor automatic (decltype). It allows everything, including forwarding which is essential for lifting functions in generic code. If abbreviated lambdas simply deducedecltype(auto)all of the above works.23
u/Denvercoder8 May 10 '22
Making parentheses that otherwise are superfluous impact semantics seems like it'll be a nightmare though.
11
u/dodheim May 11 '22 edited May 11 '22
Those parens haven't been superfluous since C++03 – even in C++11 they would inhibit automatic move in a
returnstatement.13
u/gracicot May 10 '22 edited May 11 '22
It's already like that.
[](auto x) -> decltype(auto) { return(x); }The parenthesis already makes the return type a reference. And reusing already existing semantics >> creating new or incomplete ones.Also in my mind (and for the compiler) there's a clear distinction between returning an expression and returning a named entity.
EDIT: Clarifications
2
5
u/jk-jeon May 11 '22
This seems like the most sane idea. I love it.
3
u/gracicot May 11 '22
In my opinion it is. And the nice thing is that no rules are added.
auto(x)it's a C++23 feature,decltype(auto)a C++14 feature, and the parenthesis is just a rule ofdecltype(auto). Reusing existing rules should be prioritized over creating new deduction schemes for the fun of confusing people.
0
May 10 '22
[deleted]
10
May 11 '22
In Haskell, something like this would most likely be resolved in compile time. Also in Rust, which, like C++, has guaranteed type erasure for static types.
9
u/QuotheFan May 11 '22
Haskell resolves this at compile time. In fact, it has a much stronger type checking system than C++. Hence the idiom, "If it compiles, it will most probably work"
1
u/max0x7ba https://github.com/max0x7ba May 11 '22
Python is interpreted and the type information is maintained and used at run-time.
There are Python compilers but their scope and usefulness are rather limited.
6
May 11 '22
[removed] — view removed comment
9
u/MutantSheepdog May 11 '22
How do you create closures in JS/TS without knowing it?
Don't you either need thefunctionkeyword or the arrow=>which isn't used for anything but lambdas?0
May 11 '22
[deleted]
3
May 12 '22
You can have this right now:
[]λxy(x.id() < y.id()), of course you need a macro:#define λxy(exp) (auto&& x, auto&& y) noexcept(noexcept(exp)) -> decltype(exp) { return exp; }and a keyboard shortcut to make easy to type a λ.
81
u/encyclopedist May 10 '22 edited May 10 '22
This or similar abbreviated syntaxes were proposed many times, but never got traction in the committee. For example, P0573 Abbreviated Lambdas for Fun and Profit and the author's reflection on why it was rejected. See also "Lambda lambda lambda" post by the same author with comparison of lambda syntax of multiple languages.
There are also library solutions: Boost.Lambda and Lambda2, or this, and others.