推广`...`(三个点)参数dispatch:参数集的S4方法包括`...`

时间:2014-11-17 00:52:23

标签: r argument-passing dispatch s4

实际问题

是否可以为包含 ...的一组签名参数定义方法(与...完全相对)?它不可能"开箱即用"但理论上它可能(涉及一些调整)或者这是根本不可能的事情由于S4机制的设计方式完成了吗?

我正在寻找符合

的内容
setGeneric(
  name = "foo",
  signature = c("x", "..."),
  def = function(x, ...) standardGeneric("foo")      
)
setMethod(
  f = "foo", 
  signature = signature(x = "character", "..." = "ThreedotsRelevantForMe"), 
 definition = function(x, ...) bar(x = x)
)

Martin Morgan感谢地向我指出了dotsMethods并且它说:

  

目前,“...”不能与其他正式参数混合使用:通用函数的签名只是“...”,或者它不包含“...”。 (此限制可能会在将来的版本中解除。)

背景

考虑以下尝试来概括基于...的调度机制来自一个简单的情况(只有一个更多的函数应该使用通过...传递的参数;例如在...中使用plot()将参数传递给par())到涉及以下方面的场景(取自here):

  • 当您想将参数传递给多个,因此r,收件人,
  • 当这些收件人可以位于c 调用堆栈的不同层时
  • 当他们甚至可以使用相同的参数名称但是将不同含义与他们自己的范围/闭包/框架/环境中的这些参数相关联时

另请注意,尽管这样做确实是一种好习惯,但顶级函数/接口不一定需要关注定义(很多)随后调用函数/接口的显式参数,以便正确传递参数。 IMO,这个选择应留给开发人员,因为有时一个或另一个选择更有意义。

如果我可以替换当前通过withThreedots()(AFAICT需要涉及... 的实际拆分)处理的调度,那将会很酷S4调度员不知何故,因此理想情况下只需在foo(x = x, ...)中拨打withThreedots("foo", x = x, ...)而不是foobar()

解释

withThreedots <- function(fun, ...) {
  threedots <- list(...)
  idx <- which(names(threedots) %in% sprintf("args_%s", fun))
  eval(substitute(
    do.call(FUN, c(THREE_THIS, THREE_REST)),
    list(
      FUN = as.name(fun),
      THREE_THIS = if (length(idx)) threedots[[idx]], 
      THREE_REST = if (length(idx)) threedots[-idx] else threedots
    )
  ))
}
foobar <- function(x, ...) {
  withThreedots("foo", x = x, ...)
}
foo <- function(x = x, y = "some text", ...) {
  message("foo/y")
  print(y)
  withThreedots("bar", x = x, ...)
}
bar <- function(x = x, y = 1, ...) {
  message("bar/y")
  print(y)
  withThreedots("downTheLine", x = x, ...)
}
downTheLine <- function(x = x, y = list(), ...) {
  message("downTheLine/y")
  print(y)
}

应用

foobar(x = 10) 
foobar(x = 10, args_foo = list(y = "hello world!")) 
foobar(x = 10, args_bar = list(y = 10)) 
foobar(x = 10, args_downTheLine = list(y = list(a = TRUE))) 

foobar(x = 10, 
       args_foo = list(y = "hello world!"), 
       args_bar = list(y = 10),
       args_downTheLine = list(y = list(a = TRUE))
)

# foo/y
# [1] "hello world!"
# bar/y
# [1] 10
# downTheLine/y
# $a
# [1] TRUE

概念方法(MOSTLY PSEUDO CODE)

我想我正在寻找类似的东西:

解释

setGeneric(
  name = "foobar",
  signature = c("x"),
  def = function(x, ...) standardGeneric("foobar")
)
setMethod(
  f = "foobar", 
  signature = signature(x = "ANY"), 
  definition = function(x, ...) pkg.foo::foo(x = x, ...)
)

假设:foo()在包/名称空间pkg.foo中定义

setGeneric(
  name = "foo",
  signature = c("x", "y", "..."),
  def = function(x, y = "some text", ...) standardGeneric("foo")      
)
setMethod(
  f = "foo", 
  signature = signature(x = "ANY", y = "character", "..." = "Threedots.pkg.foo.foo"), 
  definition = function(x, y, ...) {
    message("foo/y")
    print(y)
    pkg.bar::bar(x = x, ...)
  }
)

假设:bar()在包/名称空间pkg.bar中定义:

setGeneric(
  name = "bar",
  signature = c("x", "y", "..."),
  def = function(x, y = 1, ...) standardGeneric("bar")      
)
setMethod(
  f = "bar", 
  signature = signature(x = "ANY", y = "numeric", "..." = "Threedots.pkg.bar.bar"), 
  definition = function(x, y, ...) {
    message("bar/y")
    print(y)
    pkg.a::downTheLine(x = x, ...)
)
setGeneric(
  name = "downTheLine",
  signature = c("x", "y", "..."),
  def = function(x, y = list(), ...) standardGeneric("downTheLine")      
)

假设:downTheLine()在包/名称空间pkg.a中定义:

setMethod(
  f = "downTheLine", 
  signature = signature(x = "ANY", y = "list", "..." = "Threedots.pkg.a.downTheLine"), 
  definition = function(x, y, ...) {
    message("downTheLine/y")
    print(y)
    return(TRUE)
)

说明调度员需要做什么

关键部分是它必须能够区分...中与被调用的相应当前 fun相关的元素(基于常规 threedots 签名参数上的完整S4调度)以及应传递给fun可能<的函数的那些元素em>调用(即更新状态为...;类似于上面withThreedots()内发生的事情):

s4Dispatcher <- function(fun, ...) {
  threedots <- splitThreedots(list(...))
  ## --> automatically split `...`:
  ## 1) into those arguments that are part of the signature list of `fun` 
  ## 2) remaining part: everything that is not part of
  ##    the signature list and that should thus be passed further along as an 
  ##    updated version of the original `...`

  args_this <- threedots$this
  ## --> actual argument set relevant for the actual call to `fun`
  threedots <- threedots$threedots
  ## --> updated `...` to be passed along to other functions

  mthd <- selectMethod(fun, signature = inferSignature(args_this))
  ## --> `inferSignature()` would need to be able to infer the correct
  ## signature vector to be passed to `selectMethod()` from `args_this`

  ## Actual call //
  do.call(mthd, c(args_this, threedots))
}

这里是一个关于&#34;键入三点参数容器&#34;的生成器的说明。看起来像。

请注意,为了使这样的机制跨包工作,可能有意义也可以说明某个函数的命名空间(arg ns和字段.ns):

require("R6")
Threedots <- function(..., fun, ns = NULL) {
  name <- if (!is.null(ns)) sprintf("Threedots.%s.%s", ns, fun) else 
      sprintf("Threedots.%s", fun)
  eval(substitute({
    INSTANCE <- R6Class(CLASS,
      portable = TRUE,
      public = list(
        .args = "list",     ## Argument list
        .fun = "character", ## Function name
        .ns = "character",  ## Namespace of function
        initialize = function(..., fun, ns = NULL) {
          self$.fun <- fun
          self$.ns <- ns
          self$.args <- structure(list(), names = character())
          value <- list(...)
          if (length(value)) {
            self$.args <- value
          }
        }
      )
    )
    INSTANCE$new(..., fun = fun, ns = ns)
    },
    list(CLASS = name, INSTANCE = as.name(name))
  ))
}

实施例

x <- Threedots(y = "hello world!", fun = "foo", ns = "pkg.foo")

x
# <Threedots.pkg.foo.foo>
#   Public:
#     .args: list
#     .fun: foo
#     .ns: pkg.foo
#     initialize: function

class(x)
# [1] "Threedots.pkg.foo.foo" "R6" 

x$.args
# $y
# [1] "hello world!"

实际调用将如下所示:

foobar(x = 10) 
foobar(x = 10, Threedots(y = "hello world!", fun = "foo", ns = "pkg.foo")) 
foobar(x = 10, Threedots(y = 10, fun = "bar", ns = "pkg.bar")) 
foobar(x = 10, Threedots(y = list(a = TRUE), fun = "downTheLine", ns = "pkg.a"))) 

foobar(x = 10, 
       Threedots(y = "hello world!", fun = "foo", ns = "pkg.foo"),
       Threedots(y = 10, fun = "bar", ns = "pkg.bar),
       Threedots(y = list(a = 10), fun = "downTheLine", ns = "pkg.a")
)

1 个答案:

答案 0 :(得分:6)

请参阅?setGeneric并搜索“...”,然后搜索?dotsMethods。可以定义一个在...上调度的泛型(仅与其他参数不混合以进行调度)。

.A = setClass("A", contains="numeric")
.B = setClass("B", contains="A")

setGeneric("foo", function(...) standardGeneric("foo"))
setMethod("foo", "A", function(...) "foo,A-method")

setGeneric("bar", function(..., verbose=TRUE) standardGeneric("bar"),
           signature="...")
setMethod("bar", "A", function(..., verbose=TRUE) if (verbose) "bar,A-method")

导致

> foo(.A(), .B())
[1] "foo,A-method"
> bar(.A(), .B())
[1] "bar,A-method"
> bar(.A(), .B(), verbose=FALSE)
> 

我不知道这是否适合您的其他情况。