3 ms·
Same as C, define a named function, and pass a pointer to the sorting function.
by tux1968 1y ago
Same as C, define a named function, and pass a pointer to the sorting function.
- tsimionescu 1y agoAnd what if you need to close over some local variable?
- flohofwoe 1y agoNot possible, you'll need to pass the captured variables explicitly into the 'lambda' via some sort of context parameter. And considering the memory management magic that would need to be implemented by the compiler for 'painless capture' that's probably a good thing (e.g. there would almost certainly be a hidden heap allocation required which is a big no-no in Zig).
- nine_k 1y ago...or escape analysis and lifetimes, but we already have Rust %)
- pton_xd 1y agoAs far as I know lambdas in C++ will not heap allocate. Basically equivalent to manually defining a struct, with all your captures, and then stack allocating it. However if you assign a lambda to a std::function, and it's large enough, then you may get a heap allocation. Making all allocations explicit is one thing I do really like about Zig.
- andrepd 1y agoWhy would capturing require a heap allocation? Neither Rust nor C++ do this.
- flohofwoe 1y agoYou need to store the captured data somewhere if the lambda is called after the outer function returns. AFAIK C++ (or rather std::function) will heap-allocate if the capture size goes above some arbitrary limit (similar to small-string optimizations in std::string). Not sure how Rust handles this case, probably through some "I can't let you do that, Dave" restrictions ;)
- steveklabnik 1y agoThe trick is that “if”. Rust won’t ever automatically heap allocate, but if your closure does get returned to a place where the capture would be dangling, it will fail to compile. You can then choose to heap allocate it if you wish, or do something else instead. Heap allocating them is fairly rare, because most usages are in things like combinators, which have no reason to enlarge their scope like that.
- andrepd 1y agoBut that's not a closure, a closure/lambda is not an std::function. It's its own type, basically syntactic sugar for a struct with the captures vars and operator(). Of course if you want to store it on a type-erased container like std::function then you may need to heap allocate. Rust's equivalent would be a Box<dyn Fn>.
- tsimionescu 1y agoIf the lambda is a value type, you can just store whatever captures you want in the fields of this type, no need for heap allocations - they'll go on the stack just like anything else. You can even ask the user to explicitly specify which variables to capture, like in C++ lambdas, to be very explicit about the size of the lambda structure.
- flohofwoe 1y agoUnlike C you can stamp out a specialized and typesafe sort function via generics though: https://ziglang.org/documentation/master/std/#std.sort.binarySearch https://ziglang.org/documentation/master/std/#std.sort.binar...