Menu
Coddy logo textTech

Recap - Zoo Keeper

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

challenge icon

Challenge

Medium

Build a zoo of S4 classes over five files.

  • Animal.R: the virtual class Animal with the slots name and kg, the generic food_kg(a), and a show() method for Animal that prints Leo the lion eats 9.5 kg (class name in lower case, food with one decimal) and a new line.
  • Mammal.R: the virtual class Mammal, which contains Animal.
  • Lion.R and Elephant.R: mammals that eat 5% and 4% of their weight.
  • Parrot.R: an animal (not a mammal) with the extra slot word, eating 0.1 kg; its show() prints the animal line and then Polly says hello with callNextMethod().

The supplied code reads lines lion Leo 190, elephant Ella 4000 or parrot Polly 1 hello, prints every animal, the total food, the number of mammals and whether Animal is virtual.

Your code goes in Animal.R, Mammal.R, Lion.R, Elephant.R and Parrot.R. main.R holds the supplied input/output code and cannot be edited.

Try it yourself

source("Animal.R")
source("Mammal.R")
source("Lion.R")
source("Elephant.R")
source("Parrot.R")

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
zoo <- list()
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  kg <- as.numeric(p[3])
  a <- switch(p[1],
    lion = new("Lion", name = p[2], kg = kg),
    elephant = new("Elephant", name = p[2], kg = kg),
    parrot = new("Parrot", name = p[2], kg = kg, word = p[4]))
  zoo[[length(zoo) + 1]] <- a
  print(a)
}
cat(sprintf("food per day: %.1f kg", sum(vapply(zoo, food_kg, numeric(1)))), "\n", sep = "")
cat("mammals: ", sum(vapply(zoo, is, logical(1), "Mammal")), "\n", sep = "")
cat("Animal is virtual: ", isVirtualClass("Animal"), "\n", sep = "")

All lessons in Object Oriented Programming

Practice on your own: Online R compiler