Remix.run Logo
wasmperson 3 hours ago

> 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.)