Menu
Coddy logo textTech

Recap - Money and Currency

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

challenge icon

Challenge

Medium

Build a small money library in two files.

  • Money.R: the class Money (slots amount, currency) with a validity rule currency must be 3 capital letters (check with grepl("^[A-Z]{3}$", ...)); a show() method printing 12.50 EUR and a new line; + for two Money objects that stops with cannot add EUR and USD (use call. = FALSE); and Arith for Money and a number with callGeneric().
  • Convert.R: the generic convert(m, to, rates) with a method for signature("Money", "character") that converts through the rates, which say how many units of each currency make 1 EUR: 11 USD is 10 EUR.

The supplied code keeps a wallet and reads commands add 10 EUR, sum (adds the whole wallet), convert 2 USD (the second item) or double 1, printing each result or error: and the message.

Your code goes in Money.R and Convert.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Money.R")
source("Convert.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
rates <- c(EUR = 1, USD = 1.1, GBP = 0.85)
wallet <- list()
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  out <- tryCatch({
    if (p[1] == "add") {
      m <- new("Money", amount = as.numeric(p[2]), currency = p[3])
      wallet[[length(wallet) + 1]] <- m
      print(m)
    } else if (p[1] == "sum") {
      print(Reduce(`+`, wallet))
    } else if (p[1] == "convert") {
      print(convert(wallet[[as.numeric(p[2])]], p[3], rates))
    } else if (p[1] == "double") {
      print(wallet[[as.numeric(p[2])]] * 2)
    }
  }, error = function(e) cat("error: ", sub(".*object: ", "", conditionMessage(e)), "\n", sep = ""))
}

All lessons in Object Oriented Programming

Practice on your own: Online R compiler