回顾:停车计时器
本课属于 Coddy R 学习旅程的“面向对象编程”单元。第 21 课,共 57 课。
挑战
中等完成 Meter.R 中的工厂函数 make_meter(rate)。rate 表示 1 分钱可以兑换的分钟数;在工厂函数内部使用 lockBinding() 将它锁定,使其永远不能改变。计时器将剩余分钟数和已支付的分数作为私有变量保存,并返回四个函数:
insert(cents)只接受 10、20、50 或 100,否则会以coin not accepted停止;每枚硬币都会增加cents * rate分钟,并计入已支付金额。wait(minutes)让时间流逝:剩余分钟数会减少,但不会低于 0。等待时间为负数时,会以time cannot go back停止。status()返回12 min left;没有剩余时间时则返回expired。paid()返回已支付的分数。
使用 call. = FALSE。提供的代码会读取费率,然后读取 coin 20 或 wait 5 这样的行,并在每行之后打印状态,或者打印 error: 和错误消息。最后,它会打印已支付的金额,并尝试在工厂函数的环境中更改 rate。
你的代码写在 Meter.R 中。main.R 保存了提供的输入输出代码,不能编辑。
亲手试试
source("Meter.R")
# 已提供的输入/输出代码:保持原样。
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 = "")
面向对象编程中的所有课
自己练习: R 在线编译器