diff --git a/README.md b/README.md index dd63319d..6237ce65 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ The ExpenseReport example currently exists in the following languages: - [TypeScript](expensereport-typescript/) - [Visual BASIC](expensereport-vb/) - [XML/XSLT](expensereport-xslt/) +- [Zig](expensereport-zig/) ## Planned languages (in no particular order and with no guarantee) diff --git a/expensereport-zig/.gitignore b/expensereport-zig/.gitignore new file mode 100644 index 00000000..1b3f0d7a --- /dev/null +++ b/expensereport-zig/.gitignore @@ -0,0 +1,2 @@ +ExpenseReport +zig-cache/ diff --git a/expensereport-zig/ExpenseReport.zig b/expensereport-zig/ExpenseReport.zig new file mode 100644 index 00000000..476add76 --- /dev/null +++ b/expensereport-zig/ExpenseReport.zig @@ -0,0 +1,48 @@ +const std = @import("std"); +const ExpenseType = enum { DINNER, BREAKFAST, CAR_RENTAL }; +const print = std.debug.print; + +const Expense = struct { + type: ExpenseType, + amount: u32, +}; + +fn printReport(expenses: []Expense) void { + var total: u32 = 0; + var meals: u32 = 0; + + print("Expense Report: {s}\n", .{""}); + + for (expenses) |expense| { + if (expense.type == ExpenseType.DINNER or expense.type == ExpenseType.BREAKFAST) { + meals += expense.amount; + } + + var name: []const u8 = ""; + switch (expense.type) { + ExpenseType.DINNER => { name = "Dinner"; }, + ExpenseType.BREAKFAST => { name = "Breakfast"; }, + ExpenseType.CAR_RENTAL => { name = "Car Rental"; }, + } + + var mealOverExpensesMarker: []const u8 = if (expense.type == ExpenseType.DINNER and expense.amount > 5000 or expense.type == ExpenseType.BREAKFAST and expense.amount > 1000) "X" else " "; + + print("{s}\t{d}\t{s}\n", .{name, expense.amount, mealOverExpensesMarker}); + + total += expense.amount; + } + + print("Meal expenses: {d}\n", .{meals}); + print("Total expenses: {d}\n", .{total}); +} + +pub fn main() void { + var expenses: [5]Expense = .{ + Expense {.type = ExpenseType.DINNER, .amount = 5000}, + Expense {.type = ExpenseType.DINNER, .amount = 5001}, + Expense {.type = ExpenseType.BREAKFAST, .amount = 1000}, + Expense {.type = ExpenseType.BREAKFAST, .amount = 1001}, + Expense {.type = ExpenseType.CAR_RENTAL, .amount = 4}, + }; + printReport(&expenses); +} diff --git a/expensereport-zig/Makefile b/expensereport-zig/Makefile new file mode 100644 index 00000000..189f29f2 --- /dev/null +++ b/expensereport-zig/Makefile @@ -0,0 +1,17 @@ +SHELL:=/bin/bash + +export PATH:=${HOME}/Software/zig-linux-x86_64-0.9.0/:${PATH} + +.PHONY: all +all: run + +.PHONY: run +run: ExpenseReport + ./ExpenseReport + +%: %.zig + zig build-exe $^ + +.PHONY: clean +clean:: + $(RM) *.[adios] ExpenseReport