r-lib / rlang

Low-level API for programming with R
https://rlang.r-lib.org
Other
498 stars 136 forks source link

feature suggestion: has_default_args() #1621

Open vorpalvorpal opened 1 year ago

vorpalvorpal commented 1 year ago

I wonder if a has_defalut_args() function would be a good fit for rlang.

Motivating example: I have a bunch of functions of the form

f <- function(a, b, c = 1, d = "foo", e, ...){
    # computationally cheap stuff here
    out <- 1 + 2
    if (missing(a) && missing(b) && c == 1 && d == "foo" && missing(e)) return(out)
    # replace line above with
    # if (has_defualt_args()) return(out)

    # computationally expensive stuff here

    return(out)
}

Because these functions are part of an unstable project, the list of arguments for them are not stable which means that the if statement for the default arguments is not stable either. To overcome this I created the following function:

has_default_args <- function(){
  func_call <- sys.call(1)
  func <- rlang::call_name(func_call)
  args <- 
    func |> 
    get() |> 
    match.call(func_call) |> 
    rlang::call_args()
  defaults <- 
    func |> 
    get() |> 
    rlang::fn_fmls()
  map_lgl(names(args), 
          \(name) {
            if (name %notin% names(defaults)) return(FALSE)
            defaults[[name]] == args[[name]]}) |> 
    all()
}

I'm not sure if such a function would fit within rlang or not, but I thought I would suggest it anyway.

lionel- commented 1 year ago

Thanks for the idea. This looks a bit too specific for rlang though.