Menu
Coddy logo textTech

Bank Ledger

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 57 of 57.

challenge icon

Challenge

Hard

Build a small bank from Reference Classes in four files. All definitions are wrapped in suppressMessages(); use call. = FALSE in every stop().

  • Account.R: fields id, owner, balance (0 at the start). deposit(x) and withdraw(x) stop with invalid amount when x is missing or below 1; withdraw() stops with insufficient funds in 2 when the balance would go below lowest(), which is 0. month_end() does nothing; line() returns 1 ada checking: -20 using kind().
  • Checking.R: kind checking; the balance may go down to -100.
  • Savings.R: kind savings; at most 2 withdrawals per month (withdrawal limit on 2), counted only when they succeed; month_end() adds 1% interest, rounded down, and resets the count.
  • Bank.R: open_account(kind, id, owner) (account 2 exists), get_account(id) (no account 9), transfer(from, to, amount), which changes nothing when the withdrawal fails, month_end() for every account, and statement(), the lines of all accounts sorted by id.

The supplied code reads commands open checking 1 ada, dep 1 100, wd 2 30, tr 1 2 50 or month, prints ok or the error message for each, then the statement.

Your code goes in Account.R, Checking.R, Savings.R and Bank.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Account.R")
source("Checking.R")
source("Savings.R")
source("Bank.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
bank <- Bank$new()
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  n <- suppressWarnings(as.numeric(p[-1]))
  msg <- tryCatch({
    switch(p[1],
      open = bank$open_account(p[2], as.numeric(p[3]), p[4]),
      dep = bank$get_account(n[1])$deposit(n[2]),
      wd = bank$get_account(n[1])$withdraw(n[2]),
      tr = bank$transfer(n[1], n[2], n[3]),
      month = bank$month_end())
    "ok"
  }, error = function(e) conditionMessage(e))
  cat(line, ": ", msg, "\n", sep = "")
}
for (l in bank$statement()) cat(l, "\n", sep = "")

All lessons in Object Oriented Programming

Practice on your own: Online R compiler