aboutsummaryrefslogtreecommitdiff
path: root/exercises
diff options
context:
space:
mode:
authorDave Gauer <dave@ratfactor.com>2021-02-16 20:21:32 -0500
committerDave Gauer <dave@ratfactor.com>2021-02-16 20:21:32 -0500
commite32bd7ce30c8548884289483951395d4e7a4a0b7 (patch)
treeee6c37ade9eec421628fc0d623d6fb1dcd0fd941 /exercises
parent62fc8f7139a348346c7befde7cccff3076dc8cc6 (diff)
downloadziglings-e32bd7ce30c8548884289483951395d4e7a4a0b7.tar.gz
ziglings-e32bd7ce30c8548884289483951395d4e7a4a0b7.tar.bz2
ziglings-e32bd7ce30c8548884289483951395d4e7a4a0b7.tar.xz
ziglings-e32bd7ce30c8548884289483951395d4e7a4a0b7.zip
Added ex. 46 optionals 2 - elephants!
Diffstat (limited to 'exercises')
-rw-r--r--exercises/44_quiz5.zig2
-rw-r--r--exercises/46_optionals2.zig46
2 files changed, 48 insertions, 0 deletions
diff --git a/exercises/44_quiz5.zig b/exercises/44_quiz5.zig
index 88e0ff7..a3289e9 100644
--- a/exercises/44_quiz5.zig
+++ b/exercises/44_quiz5.zig
@@ -28,6 +28,8 @@ pub fn main() void {
elephantC.tail = &elephantA;
visitElephants(&elephantA);
+
+ std.debug.print("\n", .{});
}
// This function visits all elephants once, starting with the
diff --git a/exercises/46_optionals2.zig b/exercises/46_optionals2.zig
new file mode 100644
index 0000000..11f37aa
--- /dev/null
+++ b/exercises/46_optionals2.zig
@@ -0,0 +1,46 @@
+//
+// Now that we have optional types, we can apply them to structs.
+// The last time we checked in with our elephants, we had to link
+// all three of them together in a "circle" so that the last tail
+// linked to the first elephant. This is because we had NO CONCEPT
+// of a tail that didn't point to another elephant!
+//
+const std = @import("std"); // single quotes
+
+const Elephant = struct {
+ letter: u8,
+ tail: *Elephant = undefined, // <---- make this optional!
+ visited: bool = false,
+};
+
+pub fn main() void {
+ var elephantA = Elephant{ .letter = 'A' };
+ var elephantB = Elephant{ .letter = 'B' };
+ var elephantC = Elephant{ .letter = 'C' };
+
+ // Link the elephants so that each tail "points" to the next.
+ elephantA.tail = &elephantB;
+ elephantB.tail = &elephantC;
+
+ visitElephants(&elephantA);
+
+ std.debug.print("\n", .{});
+}
+
+// This function visits all elephants once, starting with the
+// first elephant and following the tails to the next elephant.
+fn visitElephants(first_elephant: *Elephant) void {
+ var e = first_elephant;
+
+ while (!e.visited) {
+ std.debug.print("Elephant {u}. ", .{e.letter});
+ e.visited = true;
+
+ // We should stop once we encounter a tail that
+ // does NOT point to another element. What can
+ // we put here to make that happen?
+ if (e.tail == null) ???;
+
+ e = e.tail.?;
+ }
+}