Skip to content

Commit

Permalink
Add ExpenseReport in Zig.
Browse files Browse the repository at this point in the history
  • Loading branch information
christianhujer committed Dec 31, 2021
1 parent 24583d6 commit 6d668eb
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 2 additions & 0 deletions expensereport-zig/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
ExpenseReport
zig-cache/
48 changes: 48 additions & 0 deletions expensereport-zig/ExpenseReport.zig
Original file line number Diff line number Diff line change
@@ -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);
}
17 changes: 17 additions & 0 deletions expensereport-zig/Makefile
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 6d668eb

Please sign in to comment.