4

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 
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 5
    You can try `all.equal` (found while reading `?identical` in the see-also part) – Tensibai Aug 28 '15 at 08:31
  • Yes, that works. Thanks. – sdgfsdh Aug 28 '15 at 08:37
  • A function consists of more than just a body. Even the body has things in addition to the text. If you want to compare only the text in the body try `identical(as.character(body(g)), as.character(body(f)))` – user20637 Aug 28 '15 at 12:22

3 Answers3

8

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.

Tensibai
  • 15,557
  • 1
  • 37
  • 57
4

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

identical(deparse(f),deparse(g))
[1] TRUE
James
  • 65,548
  • 14
  • 155
  • 193
1

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
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245