【问题标题】:In R, how do I test that two functions have the same definition?在 R 中,如何测试两个函数是否具有相同的定义?
【发布时间】:2015-08-28 08:18:48
【问题描述】:

我有两个函数,fg,定义相同:

f <- function(x) { x + 1 }
g <- function(x) { x + 1 }

但是,identical 函数认为它们不同:

identical(f, g)
FALSE

我认为这是因为它们在内存中占据了不同的区域; identical(f, f)TRUE

我只对测试具有相同定义的函数感兴趣;我可以使用其他功能吗?

行为应该是:

sameDefinition(f, f)
TRUE

sameDefinition(f, g)
TRUE

sameDefinition(f, function(x) { x + 1 })
TRUE

sameDefinition(f, function(x) { x + 3 }) 
FALSE 

# Equivalent, but different definitions
sameDefinition(f, function(x) { x + 2 - 1 }) 
FALSE 

【问题讨论】:

  • 你可以试试all.equal(在另见部分阅读?identical时发现)
  • 是的,这行得通。谢谢。
  • 一个函数不仅仅包含一个主体。就连身体也有文字之外的东西。如果您只想比较正文中的文本,请尝试identical(as.character(body(g)), as.character(body(f)))

标签: r function equality equivalent


【解决方案1】:

我的评论的长版:

引用?identical doc:

另见

all.equal 用于描述两个对象的不同之处;

在 all.equal 文档中有:

不要在 if 表达式中直接使用 all.equal——要么使用 isTRUE(all.equal(....)) 或相同(如果合适)。

所以你真的不需要函数,你可以写isTRUE(all.equal(f,g))然后完成你的任务。

【讨论】:

    【解决方案2】:

    你可以deparse函数然后检查它们是否相同:

    identical(deparse(f),deparse(g))
    [1] TRUE
    

    【讨论】:

      【解决方案3】:

      根据 Tensibai 的建议,您可以使用 all.equal 函数。需要一个包装器,因为all.equal 将在对象不相等时返回一个字符向量。

      sameDefinition <- function(x, y) { 
      
          stopifnot(is.function(x), "x must be a function")
          stopifnot(is.function(y), "y must be a function")
      
          identical(all.equal(x, y), TRUE)
      } 
      

      例子:

      sameDefinition(f, g)
      TRUE
      
      sameDefinition(f, function(x) { x + 2 - 1 })
      FALSE
      

      【讨论】:

      • 为什么不按照 all.equal 文档直接使用 isTRUE ?
      • isTRUE 只是 identical(TRUE, x) - 我想这两种方法都有效。
      • identical(TRUE, x)x == TRUE 不同。试试x &lt;- "TRUE"。您应该使用TRUE 而不是T,因为T 可以重新定义而TRUE 不能。
      • 我不知道 - 相应地更新了答案。
      猜你喜欢
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2010-11-19
      • 1970-01-01
      • 2021-03-22
      相关资源
      最近更新 更多