Dear Jan,
Here's yet another solution that takes advantage of partial matching:
> foo <- function(x, schema. = schema(x)) {
+ if (is.null(schema.)) stop("schema missing")
+ x
+ }
> schema <- function(x) attr(x, "schema")
> y <- 1
> z <- 2
> attr(y, "schema") <- "bar"
> foo(y)
[1] 1
attr(,"schema")
[1] "bar"
> foo(z)
Error in foo(z) : schema missing
> foo(z, schema="baz")
[1] 2
I hope this helps,
John
On 2022-08-08 9:10 a.m., Jan van der Laan wrote:
Not sure if this belongs on r-help or r-package-devel; decided for the
latter as the question is mainly relevant when writing code to be used
by others.
The issue I run into is that I want to write a function similar to:
foo <- function(x, schema = schema(x)) {
? if (is.null(schema)) stop("schema missing")
? # ...
}
with 'schema()' something like (strongly simplified):
schema <- function(x) attr(x, "schema")
However using both the argument schema and calling the schema() function
in one of the default arguments is not allowed ans results in the
following somewhat cryptic error message:
Error in foo(1:3) :
? promise already under evaluation: recursive default argument
reference or earlier problems?
I am looking for a clean solution to this. I can rename the argument or
function, but calling it something other than schema feels impractical
as both refer to the same thing (the schema of x). The best solution I
have come up with until now is to define a second function to be used in
default function arguments:
schema_ <- schema
foo <- function(x, schema = schema_(x)) {
? if (is.null(schema)) stop("schema missing")
? # ...
}
I guess another solution would be:
foo <- function(x, schema) {
? if (missing(schema)) schema <- schema(x)
}
But then it is not clear for the user from the interface that the
'schema' argument can be omitted.
I am hoping some of you have other suggestions.
And, is this something that could be 'fixed' in the R-parser?
Thanks,
Jan
______________________________________________ R-package-devel at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-package-devel
John Fox, Professor Emeritus McMaster University Hamilton, Ontario, Canada web: https://socialsciences.mcmaster.ca/jfox/