Recap - Zoo Keeper
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 36 of 57.
Challenge
MediumBuild a zoo of S4 classes over five files.
Animal.R: the virtual classAnimalwith the slotsnameandkg, the genericfood_kg(a), and ashow()method forAnimalthat printsLeo the lion eats 9.5 kg(class name in lower case, food with one decimal) and a new line.Mammal.R: the virtual classMammal, which containsAnimal.Lion.RandElephant.R: mammals that eat 5% and 4% of their weight.Parrot.R: an animal (not a mammal) with the extra slotword, eating 0.1 kg; itsshow()prints the animal line and thenPolly says hellowithcallNextMethod().
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
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 Meter7S4 Inheritance
Extending With containscallNextMethodVirtual ClassesChecking Types With is()Recap - Zoo Keeper2S3 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