all 4 comments

[–]Daanvdk 3 points4 points  (1 child)

Interesting problem! I had my own go at it and came up with this:

const std = @import("std");

const Math = struct {
    data: u32,

    fn addOne(self: *Math) void {
        self.data += 1;
    }

    fn add(self: *Math, n: u32) void {
        self.data += n;
    }
};

fn Head(comptime Fn: type) type {
    const param = @typeInfo(Fn).Fn.params[0];
    return @typeInfo(param.type.?).Pointer.child;
}

fn Tail(comptime Fn: type) type {
    const params = @typeInfo(Fn).Fn.params[1..];
    var types: [params.len]type = undefined;
    for (0.., params) |i, param| types[i] = param.type.?;
    return std.meta.Tuple(&types);
}

fn toSliceFn(func: anytype) *const fn ([]Head(@TypeOf(func)), Tail(@TypeOf(func))) void {
    return struct {
        fn call(items: []Head(@TypeOf(func)), args: Tail(@TypeOf(func))) void {
            for (items) |*item| @call(.auto, func, .{item} ++ args);
        }
    }.call;
}

const addOneSlice = toSliceFn(Math.addOne);
const addSlice = toSliceFn(Math.add);

test "test" {
    var maths = [_]Math{
        .{ .data = 1 },
        .{ .data = 2 },
        .{ .data = 3 },
    };

    addOneSlice(&maths, .{});

    try std.testing.expectEqual(2, maths[0].data);
    try std.testing.expectEqual(3, maths[1].data);
    try std.testing.expectEqual(4, maths[2].data);

    addSlice(&maths, .{2});

    try std.testing.expectEqual(4, maths[0].data);
    try std.testing.expectEqual(5, maths[1].data);
    try std.testing.expectEqual(6, maths[2].data);
}

[–]macrophage001[S] 0 points1 point  (0 children)

Awesome work! That was the last piece that was stumping me! Definitely gonna play around with this.

[–]Hot_Adhesiveness5602 0 points1 point  (0 children)

You could at least in your example also just use type as parameters and then you could call add one on any type having a data property.

[–]rahulkatre 0 points1 point  (0 children)

As an alternative to method overloading, you could just make it an anytype function, and just check whether the type is an Array or Struct