Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Last active July 14, 2022 05:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/d866605d31fa396667a1427e63af1a0a to your computer and use it in GitHub Desktop.
Save hnakamur/d866605d31fa396667a1427e63af1a0a to your computer and use it in GitHub Desktop.
Crate a binary tree
const std = @import("std");
const expect = std.testing.expect;
const cell = struct {
v1: ?*Variant,
v2: ?*Variant,
};
const Variant = union(enum) {
int: i32,
boolean: bool,
cell: cell,
// void can be omitted when inferring enum tag type.
none,
fn truthy(self: Variant) bool {
return switch (self) {
Variant.int => |x_int| x_int != 0,
Variant.boolean => |x_bool| x_bool,
Variant.cell => false,
Variant.none => false,
};
}
fn deinit(self: *Variant, allocator: std.mem.Allocator) void {
switch (self.*) {
.cell => |*c| {
if (c.v1) |v1| v1.deinit(allocator);
if (c.v2) |v2| v2.deinit(allocator);
},
else => {},
}
allocator.destroy(self);
}
};
test "union method" {
var v1 = Variant{ .int = 1 };
var v2 = Variant{ .boolean = false };
try expect(v1.truthy());
try expect(!v2.truthy());
}
test "create union" {
const allocator = std.testing.allocator;
var v1 = try allocator.create(Variant);
defer allocator.destroy(v1);
v1.* = .{ .int = 1 };
try expect(v1.truthy());
}
test "create union" {
const allocator = std.testing.allocator;
var top = try allocator.create(Variant);
top.* = .{ .cell = cell{ .v1 = null, .v2 = null } };
defer top.deinit(allocator);
var p = top;
var i: i32 = 0;
while (i < 3) : (i += 1) {
var left = try allocator.create(Variant);
left.* = .{ .int = i + 1 };
p.cell.v1 = left;
var right = try allocator.create(Variant);
right.* = .{ .cell = cell{ .v1 = null, .v2 = null } };
p.cell.v2 = right;
p = p.cell.v2.?;
}
try std.testing.expectEqual(@as(i32, 2), top.cell.v2.?.cell.v1.?.int);
std.log.warn("{}", .{top.cell.v2.?.cell.v1}); // top から辿ると 2 であって欲しい
}
```
$ zig test create_union_enum.zig
Test [3/3] test "create union"... [default] (warn): Variant{ .int = 2 }
All 3 tests passed.
$ zig version
0.10.0-dev.2989+4a28c1d5c
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment