Settings

Theme

Lambdas, Nested Functions, and Blocks (2021)

thephd.dev

44 points by zaikunzhang 5 months ago · 9 comments

Reader

PaulHoule 5 months ago

I always thought that if you wanted variables to be able to escape the function they were defined in you have to allocate them on the heap and then you need some kind of garbage collection.

  • SkiFire13 5 months ago

    If you want them only to "escape" down the stack then it's not necessary. If you want them to escape up the stack then of course you can't have them capture a pointer to the stack variable, because that will no longer exist once the current function returns. However if you capture all variables by value and make the lambda an unique type containing all the captured variables then you can return it up the stack. Of course the downside of this is that each lambda gets its own different type, but you can add ways to convert them to a common type at the cost of having to then deal with the allocation issue at that point.

  • ori_b 5 months ago

    You can also have some kind of heapify/free, with undefined behavior if you get it wrong.

    I think the C standards committee needs to figure out memory safety before adding any new features that are likely to interact with it.

    • PaulHoule 5 months ago

      So you're saying the runtime mallocs the pointer to the closure and it's your responsibility to free it when you don't need it anymore?

      • ori_b 5 months ago

        Kinda. Here's an example:

             void
             mkclosure(int x)
             {
                 int x;
                 void fn(void){ return x + 1; }
                 return fnheapify(fn);
             }
        
             void
             useclosure(void)
             {
                 void (^fn)(void) = mkclosure(42);
                 fn();
                 fnfree(fn);
             }
remexre 5 months ago

Are there any implementations of this lambdas proposal on top of any production-quality compilers? Or are there some updates on how this is doing in committee?

mwkaufma 5 months ago

"Unfortunately, many compiler authors would absolutely give our recommended advice a gigantic middle finger."

Simmer down, now.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection