Home > Software design >  How do I determine the number of arguments of a user-supplied function?
How do I determine the number of arguments of a user-supplied function?

Time:01-30

I have a function myfun which among other arguments has one that is a user supplied function, say f. This function may have any number of arguments, including maybe none. Here is a simple example:

myfun = function(f, ...) { f()}

Now calls to myfun might be

myfun( f=function() rnorm(10) )
myfun( f=function(m) rnorm(10, m) )

For reasons that are not relevant here I don't want to use the ellipse argument ... inside of f, so my question is whether there is any other way to determine inside of myfun how many arguments the function f has?

CodePudding user response:

A possible solution:

myfun = function(f, ...) {f(...)}

myfun( f=function() rnorm(10) )
#>  [1] -0.3336938  0.2501421  0.6088359 -1.3031804 -1.3646857  1.5234396
#>  [7]  0.4761205  0.5643735 -2.3891469 -0.4434548
myfun( f=function(m) rnorm(10, m), m=0 )
#>  [1] -0.5266229  0.8966870 -0.7263800  0.4142213 -0.5391597 -1.8312270
#>  [7] -0.2559361 -0.8140346  0.8726132 -0.6711965
myfun( f=function(x, y) rnorm(10, x, y), x=0, y=1 )
#>  [1]  1.00077751  2.10254021 -0.38788845  0.01146982 -0.90851643  1.37646202
#>  [7] -0.88601721 -0.37924904  0.79836798 -1.18670772

CodePudding user response:

This is what I may code in R.

myfun = function(f, ...) { f(...)}
myfun( f=function(m) rnorm(10, m), m )
  •  Tags:  
  • r
  • Related