복습 - 화폐와 통화
Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 31번째.
챌린지
중급두 파일로 작은 화폐 라이브러리를 만드세요.
Money.R:Money클래스(amount,currency슬롯)와currency must be 3 capital letters유효성 규칙(grepl("^[A-Z]{3}$", ...)로 확인);12.50 EUR와 줄바꿈을 출력하는show()메서드; 두Money객체에 대한+연산으로cannot add EUR and USD와 함께 중단(call. = FALSE사용); 그리고callGeneric()을 사용하는Money와 숫자에 대한Arith를 구현합니다.Convert.R:convert(m, to, rates)제네릭과signature("Money", "character")에 대한 메서드를 구현하여 환율을 통해 변환합니다. 환율은 각 통화의 몇 단위가 1 EUR에 해당하는지를 나타내며, 11 USD는 10 EUR입니다.
제공된 코드는 지갑을 유지하고 add 10 EUR, sum(전체 지갑을 더함), convert 2 USD(두 번째 항목) 또는 double 1 명령을 읽어 각 결과 또는 error: 와 메시지를 출력합니다.
코드는 Money.R과 Convert.R에 작성합니다. main.R에는 제공된 입력/출력 코드가 들어 있으며 편집할 수 없습니다.
직접 해보기
source("Money.R")
source("Convert.R")
# 제공된 입력/출력 코드: 있는 그대로 유지하세요
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 = ""))
}
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 R 컴파일러