Recap - Parking Meter
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 21 of 57.
Challenge
MediumComplete the factory make_meter(rate) in Meter.R. rate is the number of minutes one cent buys; lock it with lockBinding() inside the factory so it can never change. The meter keeps the minutes left and the cents paid as private variables and returns four functions:
insert(cents)accepts only 10, 20, 50 or 100 and otherwise stops withcoin not accepted; each coin addscents * rateminutes and counts towards the amount paid.wait(minutes)lets time pass: the minutes left go down, but never below 0. A negative wait stops withtime cannot go back.status()returns12 min left, orexpiredwhen no time is left.paid()returns the cents paid.
Use call. = FALSE. The supplied code reads the rate, then lines coin 20 or wait 5, and prints the status or error: and the message after each. Finally it prints the amount paid and tries to change rate inside the factory's environment.
Your code goes in Meter.R. main.R holds the supplied input/output code and cannot be edited.
Try it yourself
source("Meter.R")
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
meter <- make_meter(as.numeric(input[1]))
for (line in input[-1]) {
p <- strsplit(line, " ")[[1]]
msg <- tryCatch({
if (p[1] == "coin") meter$insert(as.numeric(p[2]))
if (p[1] == "wait") meter$wait(as.numeric(p[2]))
meter$status()
}, error = function(e) paste("error:", conditionMessage(e)))
cat(line, ": ", msg, "\n", sep = "")
}
cat("paid: ", meter$paid(), " cents\n", sep = "")
r <- tryCatch({ environment(meter$insert)$rate <- 0; "rate changed" }, error = function(e) "rate is locked")
cat(r, "\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 BooksPractice on your own: Online R compiler