[Rd] all.equal applied to function closures

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon Nov 30 19:36:50 CET 2020

On 30/11/2020 1:05 p.m., Kevin Van Horn via R-devel wrote:
> Consider the following code:
>      f <- function(x)function(y){x+y}
>      all.equal(f(5), f(0))
> This returns TRUE, when it should return FALSE; I think it’s hard to make the case that f(5) and f(0) are “approximately equal” in any meaningful sense. Digging into the code for all.equal(), I see that all.equal(f(5), f(0)) results in a call to all.equal.language(f(5), f(0)), which only compares the function texts for equality.
> If it is decided to leave this behavior as-is, then at least it should be documented. Currently I cannot find any documentation for all.equal applied to functions.

Clearly it should also compare the environments of the two functions, 
then it would see a difference:

 > all.equal(environment(f(5)), environment(f(0)))
[1] "Component “x”: Mean relative difference: 1"

Changing the first few lines from

     if (is.language(target) || is.function(target))
         return(all.equal.language(target, current, ...))


     if (is.function(target)) {
         msg <- all.equal.language(target, current, ...)
         if (isTRUE(msg)) {
             msg <- all.equal.environment(environment(target), 
environment(current), ...)
             if (is.character(msg))
               msg <- paste("Environments:", msg)
     if (is.language(target))
         return(all.equal.language(target, current, ...))

would fix it.

Duncan Murdoch

More information about the R-devel mailing list