Skip to content

Instantly share code, notes, and snippets.

@ljmccarthy
Last active June 6, 2022 23:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ljmccarthy/b919325223ff0d60df92c86e958c113a to your computer and use it in GitHub Desktop.
Save ljmccarthy/b919325223ff0d60df92c86e958c113a to your computer and use it in GitHub Desktop.
const std = @import("std");
const ExprType = enum {
Val,
Var,
Add,
Mul,
};
const Value = u32;
const VarName = []const u8;
const Expr = union(ExprType) {
Val: Value,
Var: VarName,
Add: BinOp,
Mul: BinOp,
};
const BinOp = struct {
lhs: *const Expr,
rhs: *const Expr,
};
fn eval(comptime expr: *const Expr, comptime Env: type, env: *const Env) Value {
switch (expr.*) {
.Val => |value| { return value; },
.Var => |name| { return @field(env, name); },
.Add => |op| { return eval(op.lhs, Env, env) + eval(op.rhs, Env, env); },
.Mul => |op| { return eval(op.lhs, Env, env) * eval(op.rhs, Env, env); },
}
}
const myexpr = Expr{
.Mul = BinOp{
.lhs = &Expr{.Val = 42},
.rhs = &Expr{
.Add = BinOp{
.lhs = &Expr{.Var = "x"},
.rhs = &Expr{.Var = "x"}}}}};
pub fn main() !void {
var randomByte: [1]u8 = undefined;
try std.os.getRandomBytes(randomByte[0..]);
var myenv = (struct {x: Value}) {.x = randomByte[0]};
const result = eval(&myexpr, @typeOf(myenv), &myenv);
std.debug.warn("result: {}\n", result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment