Menu
Coddy logo textTech

Recap - Temperatures

Part of the Object Oriented Programming section of Coddy's R journey. Lesson 6 of 57.

challenge icon

Challenge

Medium

Build 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 with stopifnot() and returns structure(value, unit = unit, class = "temperature").
  • validate_temperature(x) stops with unit must be C or F, or with below absolute zero when the value is below -273.15 C or -459.67 F.
  • temperature(value, unit = "C") converts the value with as.double(), upper-cases the unit and returns a validated temperature.
  • format.temperature() returns 21.5 C with one decimal place, and print.temperature() prints Temperature: 21.5 C and returns invisible(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

Practice on your own: Online R compiler