Recap - Temperatures
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 6 of 57.
Challenge
MediumBuild the S3 class temperature in Temperature.R. A temperature is a number with an attribute unit (C or F).
new_temperature(value, unit)checks the types withstopifnot()and returnsstructure(value, unit = unit, class = "temperature").validate_temperature(x)stops withunit must be C or F, or withbelow absolute zerowhen the value is below -273.15 C or -459.67 F.temperature(value, unit = "C")converts the value withas.double(), upper-cases the unit and returns a validated temperature.format.temperature()returns21.5 Cwith one decimal place, andprint.temperature()printsTemperature: 21.5 Cand returnsinvisible(x).convert_to(t, unit)returns a temperature in the given unit (the same value when the unit already matches).
Use call. = FALSE in every stop(). The supplied code reads lines 21.5 c F (value, unit, target unit), prints the temperature and the converted one, or error: and the message.
Your code goes in Temperature.R. main.R holds the supplied input/output code and cannot be edited.
Try it yourself
source("Temperature.R")
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
for (line in input) {
p <- strsplit(line, " ")[[1]]
result <- tryCatch({
t <- temperature(p[1], p[2])
print(t)
print(convert_to(t, p[3]))
NULL
}, error = function(e) cat("error: ", 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 BooksPractice on your own: Online R compiler