Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how do I test that two functions have the same definition?

I have two functions, f and g, which have the same definition:

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

However, the identical function considers them different:

identical(f, g)
FALSE

I presume this is because they occupy different areas in memory; identical(f, f) gives TRUE.

I am only interested in testing that the functions having the same definition; is there another function I can use for this?

The behaviour should be:

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 
like image 376
sdgfsdh Avatar asked Dec 15 '22 12:12

sdgfsdh


1 Answers

Long version of my comment:

Quote of ?identical doc:

See Also

all.equal for descriptions of how two objects differ;

In the all.equal doc there's:

Do not use all.equal directly in if expressions—either use isTRUE(all.equal(....)) or identical if appropriate.

So you don't really need a function, you can write isTRUE(all.equal(f,g)) and be done with your task.

like image 83
Tensibai Avatar answered May 06 '23 00:05

Tensibai