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:

  1. We define generic functions area and perim using UseMethod().

  2. Instead of an interface, we create separate classes for rect and circle using R’s S3 class system.

  3. We implement methods for these classes using the naming convention functionname.classname.

  4. The measure function works with any object that has area and perim methods defined.

  5. In the main function, we create instances of rect and circle and call measure 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.