The @as(i64, c - '0') pattern is starting to repeat. Add a tiny helper to cut the noise:
fn digit(c: u8) i64 {
return @as(i64, c - '0');
}
Then digit(input[0]) instead of @as(i64, input[0] - '0').
Handle all four operators. Read input[1] and use a switch. In your main add this:
check("3+5", 8);
check("9-3", 6);
check("4*7", 28);
check("8/2", 4);
In Zig switch works like this:
const month: i64 = 2;
const month_string: []const u8 = switch (month) {
0 => "Jan",
1 => "Feb",
else => "got bored typing this already",
};
For division, use @divTrunc(a, b) -- Zig insists you be explicit about truncation.
fn eval(input: []const u8) i64 {
const a: i64 = digit(input[0]);
const op: u8 = input[1];
const b: i64 = digit(input[2]);
return switch (op) {
'+' => a + b,
'-' => a - b,
'*' => a * b,
'/' => @divTrunc(a, b),
else => 0,
};
}
Four oks. We can evaluate any single-operator expression on two single digits. It's not much -- but think about what just happened. A string went in. A number came out. That's the whole game. Everything from here is just making the string more interesting.