From 7a995ea2feaaacdb4be49c7f96c77020dd8f85af Mon Sep 17 00:00:00 2001 From: Tomasz Kalinowski Date: Wed, 6 Nov 2024 11:13:02 -0500 Subject: [PATCH 1/3] fix unary Ops methods: -, +, ! --- R/method-ops.R | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/R/method-ops.R b/R/method-ops.R index a39ee00b..5e5117f2 100644 --- a/R/method-ops.R +++ b/R/method-ops.R @@ -17,7 +17,12 @@ on_load_define_ops <- function() { #' @export Ops.S7_object <- function(e1, e2) { cnd <- tryCatch( - return(base_ops[[.Generic]](e1, e2)), + return( + if (missing(e2)) + base_ops[[.Generic]](e1) + else + base_ops[[.Generic]](e1, e2) + ), S7_error_method_not_found = function(cnd) cnd ) From 0ad14b6dd801a913c42f86efb7cb93c41e15b01b Mon Sep 17 00:00:00 2001 From: Tomasz Kalinowski Date: Wed, 6 Nov 2024 11:23:16 -0500 Subject: [PATCH 2/3] also check `missing(e2)` in fallback. --- R/method-ops.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/R/method-ops.R b/R/method-ops.R index 5e5117f2..0617940c 100644 --- a/R/method-ops.R +++ b/R/method-ops.R @@ -26,7 +26,7 @@ Ops.S7_object <- function(e1, e2) { S7_error_method_not_found = function(cnd) cnd ) - if (S7_inherits(e1) && S7_inherits(e2)) { + if (S7_inherits(e1) && (missing(e2) || S7_inherits(e2))) { stop(cnd) } else { # Must call NextMethod() directly in the method, not wrapped in an From f75e089526bd59d217aeb9f42b5f9dcbab51c7ce Mon Sep 17 00:00:00 2001 From: Tomasz Kalinowski Date: Wed, 6 Nov 2024 11:25:26 -0500 Subject: [PATCH 3/3] add test --- tests/testthat/test-method-ops.R | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/tests/testthat/test-method-ops.R b/tests/testthat/test-method-ops.R index d825b65e..2dfd1fec 100644 --- a/tests/testthat/test-method-ops.R +++ b/tests/testthat/test-method-ops.R @@ -122,3 +122,13 @@ test_that("Ops methods can use super", { expect_equal(foo2(1L) + 1, foo2(2L)) }) + + +test_that("Unary Ops methods work", { + Double := new_class(class_double) + method(`-`, list(Double, class_missing)) <- function(e1, e2) { + Double(-as.double(e1)) + } + + expect_identical(-Double(1), Double(-1)) +})