How to compare functions?

后端 未结 3 370
醉酒成梦
醉酒成梦 2020-11-29 12:00

Is there a way to compare whether two function objects are the same?

m <- mean
m == mean ## don\'t work

## this seems not to be the correct way:
function         


        
相关标签:
3条回答
  • 2020-11-29 12:38

    You can convert the functions to strings, and compare those strings.

    equal_functions <- function(f,g)
      all( 
        capture.output(print(f)) ==
        capture.output(print(g))
      )
    equal_functions(function(x) x, function(x) x) # TRUE
    

    But functions that differ for non-essential reasons will be seen as different.

    equal_functions(function(x) x, function(u) u) # FALSE
    equal_functions(
      function(x) x, 
      function(x) 
        x
    ) # FALSE
    
    0 讨论(0)
  • 2020-11-29 12:51

    I use isTRUE(all.equal(function1,function2)), but this suffers from similar drawbacks to the other methods.

    Interestingly though, all.equal gives a nice summary of how the two operands differ (try all.equal(function1,function2).

    0 讨论(0)
  • 2020-11-29 12:52

    You can use identical:

    identical(m,mean)
    
    0 讨论(0)
提交回复
热议问题