4

Can you write a function that prints out its own name?

(without hard-coding it in, obviously)

nsheff
  • 3,063
  • 2
  • 24
  • 29
  • 3
    `sys.calls` can provide that information. Take a look at: http://stackoverflow.com/questions/7307987/logging-current-function-name – vcsjones Dec 01 '11 at 21:31
  • Note this: http://stackoverflow.com/questions/7754901/the-art-of-r-programming-where-else-could-i-find-the-information/7755926#7755926 – G. Grothendieck Dec 01 '11 at 22:41
  • This question screams for the response, "what is the problem you are trying to solve?" There have been, after all, contests based on this question. One such required the code to compile and run when designated as any of several disparate languages. – Carl Witthoft Dec 02 '11 at 02:05

3 Answers3

8

You sure can.

fun <- function(x, y, z) deparse(match.call()[[1]])
fun(1,2,3)
# [1] "fun"
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • In my answer I try to explain why "You sure can." is a bit too strong a statement ;-) – Tommy Dec 01 '11 at 23:02
  • @Tommy: And that's why I +1'd your answer. I don't mean to imply that "can" means it's easy. – Joshua Ulrich Dec 01 '11 at 23:14
  • Also, `match.call` seems to be a bit overkill - it basically just uses the `sys.call` default value in your case (but it can do much more). – Tommy Dec 02 '11 at 00:38
6

You can, but just in case it's because you want to call the function recursively see ?Recall which is robust to name changes and avoids the need to otherwise process to get the name.

Recall package:base R Documentation

Recursive Calling

Description:

‘Recall’ is used as a placeholder for the name of the function in
which it is called.  It allows the definition of recursive
functions which still work after being renamed, see example below.
Community
  • 1
  • 1
mdsumner
  • 29,099
  • 6
  • 83
  • 91
6

As you've seen in the other great answers here, the answer seems to be "yes"...

However, the correct answer is actually "yes, but not always". What you can get is actually the name (or expression!) that was used to call the function.

First, using sys.call is probably the most direct way of finding the name, but then you need to coerce it into a string. deparse is more robust for that.

myfunc <- function(x, y=42) deparse(sys.call()[[1]])

myfunc (3) # "myfunc"

...but you can call a function in many ways:

lapply(1:2, myfunc) # "FUN"
Map(myfunc, 1:2) # (the whole function definition!)
x<-myfunc; x(3)   # "x"
get("myfunc")(3) # "get(\"myfunc\")"

The basic issue is that a function doesn't have a name - it's just that you typically assign the function to a variable name. Not that you have to - you can have anonymous functions - or assign many variable names to the same function (the x case above).

Tommy
  • 39,997
  • 12
  • 90
  • 85