Anonymous functions/lambdas

Technically, yes you can but it’s not quite like a Java/C++ lambda (where there is a specific syntax for an anonymous function or closure).

Basically, because struct declarations are anonymous, you can declare a struct and return the member function from said struct. So for instance, in the HashMap implementation, here you can see they are creating a generic equality function:

pub fn getAutoEqlFn(comptime K: type, comptime Context: type) (fn (Context, K, K) bool) {
    return struct {
        fn eql(ctx: Context, a: K, b: K) bool {
            _ = ctx;
            return meta.eql(a, b);
        }
    }.eql;
}

Now this example is stateless so you’ll probably want to play around with stateful alternatives.

Basically Zig really, really does not like to allocate things if it isn’t absolutely necessary and a lot of closure implementations will take that liberty on your behalf - Zig won’t. Besides, you’d have to pass an allocator to the closure itself to give it the capability to allocate in the canonical sense. I don’t see closures making it into the language any time soon or even at all.

Furthermore, a lot of lambda-function like behavior can be achieved using meta programming. So for instance, I can create a comptime parameter of anytype “comptime foo: anytype” and then use that to generically dispatch on internals. I do a lot of that here: ZEIN/src/tensor_ops.zig at main · andrewCodeDev/ZEIN · GitHub

For instance, I am dispatching on different arithmetic functions generically for AVX instructions:

arithmeticDispatch(addGeneric, x, y, z); // addition dispatch
arithmeticDispatch(subGeneric, x, y, z); // subtraction dispatch
arithmeticDispatch(mulGeneric, x, y, z); // multiplication dispatch

The two approaches can be combined to make lambda-esque functionality but to answer your question, no - there is not a current specified and particularized lambda syntax.

5 Likes