#I want to return a comptime function based on runtime switch value

1 messages · Page 1 of 1 (latest)

honest dome
#
    const compFn = switch (direction) {
        .Right => Position.generateCompFn("x", .Less),
        .Down => Position.generateCompFn("y", .Less),
        .Left => Position.generateCompFn("x", .Greater),
        .Up => Position.generateCompFn("y", .Greater),
    };

direction is runtime, all results can be comptime -calculated.
but Zig doesn't want me to:

value with comptime-only type 'fn (void, main.Position, main.Position) bool' depends on runtime control flow

why?

coarse ridge
#

the result of each switch prong is comptime known but the final result of compFn isnt

#

put & in front of either the switch or the functions to get a function pointer which can be runtime known

honest dome
#

thank you! it helped for that case. but I wanted to also switch and use different sorting methods, can you enlighten me why this approach is not enough here?

        const sortFn = &switch (direction) {
            .Right, .Down => std.sort.min,
            .Left, .Up => std.sort.max,
        };
coarse ridge
#

i assume because those functions are generic, theyre inherently comptime only

honest dome
#

ah, you're correct

#

they accept comptime args

#

hmm, but now I cannot pass/use that const pointer to function in a call to min/max:

error: expected type 'fn (void, main.Position, main.Position) bool', found '*const fn (void, main.Position, main.Position) bool'
            .Right, .Down => std.sort.min(Position, matching_walls.items, {}, compFn),
#

like so:

        const wall = switch (direction) {
            .Right, .Down => std.sort.min(Position, matching_walls.items, {}, compFn),
            .Left, .Up => std.sort.max(Position, matching_walls.items, {}, compFn),
        };
#

and I cannot dereference it either

#

I'm too beginner for what I'm trying to do but I don't want to write repeated code.