Recap - Money and Currency
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 31 of 57.
Challenge
MediumBuild a small money library in two files.
Money.R: the classMoney(slotsamount,currency) with a validity rulecurrency must be 3 capital letters(check withgrepl("^[A-Z]{3}$", ...)); ashow()method printing12.50 EURand a new line;+for twoMoneyobjects that stops withcannot add EUR and USD(usecall. = FALSE); andArithforMoneyand a number withcallGeneric().Convert.R: the genericconvert(m, to, rates)with a method forsignature("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
1S3 Basics
Working With FilesLists With a ClassConstructor FunctionsPrint and Format MethodsValidators and HelpersRecap - Temperatures4Encapsulation in R
Closures as ObjectsEnvironments as ObjectsAccessor FunctionsGuarding StateRecap - Parking Meter2S3 Generics and Methods
Generics and UseMethodDefault MethodsMethods for Base GenericsNextMethod BasicsRecap - Shape Areas8Reference Classes
Defining Reference ClassesMethods and Field UpdatesCopy SemanticsInheritance and callSuperRecap - Task Queue11Project: Library Management
Books and MembersBorrowing Books3S3 Inheritance
Class VectorsMethod Lookup OrderExtending With NextMethodChecking With inherits()Recap - Staff Payroll6S4 Generics and Methods
Creating GenericsMethods for Built-insDispatch on Two ArgumentssetValidity and validObjectRecap - Money and CurrencyPractice on your own: Online R compiler