Remix.run Logo
uecker 4 hours ago

Lambdas are just anonymous nested functions. But I like named nested functions more because they are more readable and would prefer them in most cases. Ideally you have both as most languages have.

I always wondered why C++ only added lambdas, but observing WG21 for a while, I assume this is just a random walk in language design. (not that it is different in WG14)

wasmperson 3 hours ago | parent | next [-]

> Lambdas are just anonymous nested functions.

The important feature of lambdas is that they are expressions, not that they lack a name. The advantage of function expressions is you can write the body of the function exactly at the place where it is used. With GCC nested functions you either have to write the body of the function before its first use or else write the declaration of the function twice.

This matters for long chains of continuation passing:

  foo(arg1, arg2, [](){
          // do some work
          bar(arg3, arg4, [](){
                  // do some more work
                  baz(arg5, arg6, [](){
  
                  });
          });
  });
Compare to the following, where the control flow is all out of order:

  void cb(void){
          // Do some work
          void cb2(void){
                  // do some more work
                  void cb3(void){

                  }
                  baz(arg5, arg6, cb3);
          }
          bar(arg3, arg4, cb2);
  }
  foo(arg1, arg2, cb);
uecker 3 hours ago | parent [-]

I agree with your point.

But I usually prefer the later anyway, because the code usually is not as nested anyway and having a name is often helpful, and also because I find the nested code with lambdas also not too readable. Other languages have better syntax for chaining functions in this way, i.e. with lambdas I would like to write like this:

  foo(arg1, arg2, _)
     .(int(int x)) { ... }
     .(int(int y)) { ... };
(edit: or something, I think I got it a bit wrong, but you get the idea)

But I agree, sometimes lambdas are better so it would be good to have both.

(There is the classical hack to define lambdas using statement expressions and nested functions.)

eru 3 hours ago | parent | prev [-]

I can write numbers like three by just writing 3 in my code. When I want a named number I use a syntax like x = 3. Why should functions be any different? A language doesn't need different ways to name things for each type of thing. Integers, strings, functions etc: they can all use the same mechanism for naming.

uecker 3 hours ago | parent [-]

I agree if your language is designed like this from the beginning as functional languages are, but in C you already have different syntax for functions. (edit: rephrased)