sdgfsdh
sdgfsdh

Reputation: 37095

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 

Upvotes: 5

Views: 1666

Answers (3)

sdgfsdh
sdgfsdh

Reputation: 37095

As suggested by Tensibai, you can use the all.equal function. A wrapper is required since all.equal will return a character vector when the objects are not 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)
} 

Examples:

sameDefinition(f, g)
TRUE

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

Upvotes: 1

James
James

Reputation: 66844

You could deparse the functions and then check if they are identical:

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

Upvotes: 5

Tensibai
Tensibai

Reputation: 15784

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.

Upvotes: 9

Related Questions