Операторы равенства

Перегрузка операторов

new_point <- function(x, y) {
  structure(list(x = x, y = y), class = "Point")
}

# One method for the comparison operators
Ops.Point <- function(e1, e2) {
  same <- e1$x == e2$x && e1$y == e2$y
  switch(.Generic,
         "==" = same,
         "!=" = !same,
         stop("unsupported operator: ", .Generic))
}

p1 <- new_point(1, 1)
p2 <- new_point(2, 2)
p3 <- new_point(1, 1)

equal1 <- p1 == p2
# equal1 = FALSE
equal2 <- p1 == p3
# equal2 = TRUE
equal3 <- p1 != p3
# equal3 = FALSE

cat("equal1 =", equal1, "\n")
cat("equal2 =", equal2, "\n")
cat("equal3 =", equal3, "\n")

# Any other operator gets the error
msg <- tryCatch(p1 < p2, error = conditionMessage)
# msg = unsupported operator: <
cat("msg =", msg, "\n")