Interfaces in R Programming Language
In R, we don’t have a direct equivalent of interfaces, but we can achieve similar functionality using S3 classes and generic functions. Here’s how we can implement the geometric shapes example:
library(methods)
# Define generic functions for area and perimeter
area <- function(shape) {
UseMethod("area")
}
perim <- function(shape) {
UseMethod("perim")
}
# Define rect class
rect <- function(width, height) {
structure(list(width = width, height = height), class = "rect")
}
# Implement methods for rect
area.rect <- function(shape) {
shape$width * shape$height
}
perim.rect <- function(shape) {
2 * shape$width + 2 * shape$height
}
# Define circle class
circle <- function(radius) {
structure(list(radius = radius), class = "circle")
}
# Implement methods for circle
area.circle <- function(shape) {
pi * shape$radius^2
}
perim.circle <- function(shape) {
2 * pi * shape$radius
}
# Generic measure function
measure <- function(shape) {
cat("Shape:", class(shape), "\n")
cat("Area:", area(shape), "\n")
cat("Perimeter:", perim(shape), "\n")
cat("\n")
}
# Main function
main <- function() {
r <- rect(width = 3, height = 4)
c <- circle(radius = 5)
measure(r)
measure(c)
}
# Run the main function
main()
This R code implements a similar structure to the original example. Here’s a breakdown of the changes:
We define generic functions
area
andperim
usingUseMethod()
.Instead of an interface, we create separate classes for
rect
andcircle
using R’s S3 class system.We implement methods for these classes using the naming convention
functionname.classname
.The
measure
function works with any object that hasarea
andperim
methods defined.In the
main
function, we create instances ofrect
andcircle
and callmeasure
on them.
When you run this code, you’ll get output similar to:
Shape: rect
Area: 12
Perimeter: 14
Shape: circle
Area: 78.53982
Perimeter: 31.41593
This R implementation provides similar functionality to the original Go code, demonstrating how to work with multiple shapes using a common interface-like structure in R.