自定义运算符

运算符重载

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

# Any name between % signs is a new operator
`%pow%` <- function(point, power) {
  new_point(point$x ^ power, point$y ^ power)
}

p1 <- new_point(2, 3) %pow% 3
# p1$x = 8
# p1$y = 27

p2 <- new_point(2, 3) %pow% 2
# p2$x = 4
# p2$y = 9

cat("p1$x =", p1$x, "\n")
cat("p1$y =", p1$y, "\n")
cat("p2$x =", p2$x, "\n")
cat("p2$y =", p2$y, "\n")