[ prog / sol / mona ]

prog


Zig

8 2023-10-15 18:38

>>6
Here I just cooked this up:

const std = @import("std");

pub fn Eval(comptime sexpr: anytype) type {
    return switch (sexpr[0]) {
        .add => u32,
        .print => void,
        else => @compileError("invalid opcode"),
    };
}

pub fn eval(comptime sexpr: anytype) Eval(sexpr) {
    switch (sexpr[0]) {
        .add => {
            var ret: u32 = 0;
            inline for (1..sexpr.len) |i| {
                ret += sexpr[i];
            }
            return ret;
        },

        .print => {
            inline for (1..sexpr.len) |i| {
                std.debug.print("-> {any}\n", .{sexpr[i]});
            }
        },

        else => @compileError("invalid opcode"),
    }
}

test {
    std.debug.print("{d}\n", .{eval(.{ .add, 1, 2, 3 })});

    eval(.{ .print, .lol, 777, "hello world" });
}
30


VIP:

do not edit these