#map3 how to infer array size and type at compile time?

1 messages · Page 1 of 1 (latest)

lunar fractal
#

I made a map function over 3 elements. Is there a way I don't have to pass in the array length?

// You can edit this code!
// Click into the editor and start typing.
const std = @import("std");
const builtin = @import("builtin");

fn map3(comptime T: type, comptime n: usize, array: [n]T, callback: (fn (x: T, y: T, z: T) [3]T)) [n]T {
    var result: [n]T = .{0} ** 6;
    var i: usize = 0;
    while (i < n) : (i = i + 3) {
        const x, const y, const z = callback(array[i + 0], array[i + 1], array[i + 2]);
        result[i + 0] = x;
        result[i + 1] = y;
        result[i + 2] = z;
    }
    return result;
}

pub fn main() void {
    const array: [6]f32 = .{ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 };
    const mapped = map3(f32, array.len, array, struct {
        pub fn map(x: f32, y: f32, z: f32) [3]f32 {
            return .{ z, y, x };
        }
    }.map);
    std.debug.print("Hello, {any}! (using Zig version: {})", .{ mapped, builtin.zig_version });
}
tacit bramble
#

@typeInfo(@TypeOf(array)).array.len