Last active
June 6, 2022 23:12
-
-
Save ljmccarthy/b919325223ff0d60df92c86e958c113a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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