Recap - Shape Areas
Part of the Object Oriented Programming section of Coddy's R journey. Lesson 11 of 57.
Challenge
MediumBuild a small shape library over four files. The constructors are given.
Shape.R: the genericsarea(shape, ...),perimeter(shape, ...)anddescribe(shape, ...). The defaultarea()andperimeter()methods stop withunknown shape: hexagon(usecall. = FALSE). The defaultdescribe()returnscircle: area 3.14, perimeter 6.28, built from the shape's first class and the two generics, with two decimal places.Circle.R,Rectangle.R,Triangle.R: theareaandperimetermethods of each shape. A triangle has the sidesa,b,c; its area issqrt(s * (s - a) * (s - b) * (s - c))withshalf the perimeter.
The supplied code reads lines circle 1, rectangle 2 3, triangle 3 4 5 or any other name, prints describe() or error: and the message, and finally the total area.
Your code goes in Shape.R, Circle.R, Rectangle.R and Triangle.R. main.R holds the supplied input/output code and cannot be edited.
Try it yourself
source("Shape.R")
source("Circle.R")
source("Rectangle.R")
source("Triangle.R")
# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
total <- 0
for (line in input) {
p <- strsplit(line, " ")[[1]]
n <- as.numeric(p[-1])
s <- switch(p[1],
circle = new_circle(n[1]),
rectangle = new_rectangle(n[1], n[2]),
triangle = new_triangle(n[1], n[2], n[3]),
structure(list(), class = p[1]))
out <- tryCatch({
total <- total + area(s)
describe(s)
}, error = function(e) paste("error:", conditionMessage(e)))
cat(out, "\n", sep = "")
}
cat(sprintf("total area: %.2f", total), "\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