Skip to content
Prev 8299 / 12125 Next

[R-pkg-devel] Using function with same name as argument as default argument

I kind of prefer Ivan's solution.  A variation on Andrew's that doesn't 
require you to code the default in two places is:

foo <- function(x, schema = schema(x)) {
   if (missing(schema)) {
     default <- substitute(schema)
     rm(schema)
     schema <- eval(default)
   }
}

You could also change the name of the argument and let users rely on 
partial argument matching:


foo <- function(x, schema. = schema(x)) {
    schema <- schema.   # if you don't want to type the dot again
    if (is.null(schema)) stop("schema missing")
    # ...
}

This allows users to say foo(x, schema = myschema(x)) .

However, I'd say it's not a great design.  Probably changing your 
function name to `getSchema` would be the best overall solution:


foo <- function(x, schema = getSchema(x)) {
    if (is.null(schema)) stop("schema missing")
    # ...
}

Functions do actions, so their names should be verb-like.

Duncan Murdoch
On 08/08/2022 10:23 a.m., Jan van der Laan wrote: