How to define and use a function as parameter?

Hello @aiac! Welcome to the forum.

Please check out this related thread: Anonymous functions/lambdas - Help - Ziggit

It has several examples of what I believe you are looking for. If you still have questions, feel free to follow up!

– edit

I wanted to post a few more examples because the relation between these two threads may be a bit cryptic at a first glance. You can easily use the “anytype” parameter type as a way to generically take in functions as compile time arguments. (Please note that you can take in function pointers as well, the example that I am giving here is comptime oriented, but you can deduce the type of function pointers as well).

Here we have a dispatching function that takes in a binary function as a first parameter:

fn arithmeticDispatch(    
    comptime BinaryFunc: anytype, 
    x: anytype,
    y: anytype,
    z: anytype,
) void { ...

Here we have a generic function that can be passed to that parameter:

inline fn addGeneric(x: anytype, y: anytype) @TypeOf(x) {
    return x + y;
}

Finally, here we have the dispatching call being made that binds the two:

arithmeticDispatch(addGeneric, x, y, z);

Another parameter declaration pattern from that same thread was made by @krilcebre (with @dude_the_builder 's edit):

pub fn all(comptime T:type, buf: []const T, comptime predicate: (fn (val: T) bool)) bool {
    return for (buf) |val| {
        if (!predicate(val)) break false;
    } else true;
}

// ...

all(i32, arr_1[0..], struct {
    pub fn eql(val: i32) bool { return val == 1; }
}.eql)

The take-away from that last example is the (fn (val: T) bool) as the predicate argument in the parent function “all”

4 Likes