Bank ledger in Mojo
An account struct that guards its own balance and keeps a running history.
struct Account(Movable):
var owner: String
var cents: Int
var history: List[String]
def __init__(out self, var owner: String, opening: Int):
self.owner = owner^
self.cents = opening
self.history = List[String]()
def deposit(mut self, amount: Int) raises:
if amount <= 0:
raise Error("deposit must be positive")
self.cents += amount
self.history.append("deposit " + String(amount))
def withdraw(mut self, amount: Int) raises:
if amount > self.cents:
raise Error("insufficient funds")
self.cents -= amount
self.history.append("withdraw " + String(amount))
def balance(self) -> String:
return String(self.cents // 100) + "." + String(self.cents % 100)
def attempt(mut account: Account, action: String, amount: Int):
try:
if action == "deposit":
account.deposit(amount)
else:
account.withdraw(amount)
print("ok ", action, amount)
except e:
print("rejected", action, amount, "--", String(e))
def main():
var account = Account("Ada", 5000)
attempt(account, "deposit", 1250)
attempt(account, "withdraw", 800)
attempt(account, "deposit", -40)
attempt(account, "withdraw", 99999)
attempt(account, "deposit", 375)
print("")
print("ledger for", account.owner)
for entry in account.history:
print(" ", entry)
print("closing balance:", account.balance())
How it works
Accountowns itsownername and aList[String]of entries.depositandwithdraware markedraisesand reject bad amounts withError.attemptwraps each call intry, so a rejection prints instead of stopping the run.- The closing report replays the history and formats the balance in dollars.
Keywords and builtins used here
ErrorIntListMovableStringattemptbalancedefdepositelseexceptforifmainprintraisereturnselfstructtryvarwithdraw
The run, in numbers
- Lines
- 50
- Characters to type
- 1256
- Tokens
- 351
- Three-star pace
- 75 tpm
At the three-star pace of 75 tokens a minute, this run takes about 281 seconds.
Step 1 of 2 in Encore, step 21 of 22 in Structs & traits.