【问题标题】:`vec_arith` double dispatch error with packages`vec_arith` 包的双重分派错误
【发布时间】:2021-03-14 07:51:53
【问题描述】:

我正在尝试实现 vctrs 包,但具体而言,我正在尝试使 vec_arith 双调度工作。

如果我将它加载到全局环境中,下面的示例代码可以工作,但是如果从它自己的包命名空间中调用,它似乎找不到正确的调度。

#' @import vctrs
NULL

#' @export
foo <- function(x = double()) new_vctr(x, class = "Foo")

#' @export
vec_arith.Foo <- function(op, x, y, ...){
  UseMethod("vec_arith.Foo", y)
}

#' @export
vec_arith.Foo.default <- function(op, x, y, ...){
  stop_incompatible_op(op, x, y)
}

#' @export
vec_arith.Foo.Foo <- function(op, x, y, ...) {
  switch(op,
         "+" = foo(vec_data(x)+vec_data(y)),
         stop_incompatible_op(op, x, y))
}

# After build

library(foo)
foo(1) + foo(2)
#Error in UseMethod("vec_arith.Foo", y) : 
#  no applicable method for 'vec_arith.Foo' applied to an object of class "c('Foo',     'vctrs_vctr')"
foo(1) + 2
#Error in UseMethod("vec_arith.Foo", y) : 
#  no applicable method for 'vec_arith.Foo' applied to an object of class "c('double', 'numeric')"
2 + foo(1)
#Error: <double> + <Foo> is not permitted
#Run `rlang::last_error()` to see where the error occurred.

如果你只用这个文件构建一个包,有人可以告诉我这是否可以重现吗?

我不知道它是否重要,但描述文件看起来像这样:

Package: foo
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Author: Who wrote it
Maintainer: The package maintainer <yourself@somewhere.net>
Description: More about what it does (maybe more than one line)
    Use four spaces when indenting paragraphs within the Description.
License: What license is it under?
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.1.1
Imports:
  vctrs
Roxygen: list(markdown = TRUE)

【问题讨论】:

    标签: r double-dispatch vctrs


    【解决方案1】:

    我想通了……

    您至少需要在 roxygen2 中包含以下文档,以便 S3 方法正确导出

    #' @method vec_arith.Foo Foo
    #' @export
    vec_arith.Foo.Foo <- function(op, x, y, ...) {
      switch(op,
             "+" = foo(vec_data(x)+vec_data(y)),
             stop_incompatible_op(op, x, y))
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-17
      • 1970-01-01
      • 2016-10-09
      • 2021-12-10
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多