Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace .validLHS() with tryCatch()? #88

Open
krivit opened this issue Nov 14, 2024 · 2 comments
Open

Replace .validLHS() with tryCatch()? #88

krivit opened this issue Nov 14, 2024 · 2 comments

Comments

@krivit
Copy link
Member

krivit commented Nov 14, 2024

The ultimate test of whether something can be assigned to is to actually try assigning to it.

It may therefore make sense to replace the

  if(.validLHS(xn,parent.frame())){  #If x not anonymous, set in calling env 
    on.exit(eval.parent(call('<-', xn, x)))
  }
  invisible(x) 

pattern with the much simpler

  on.exit(try(eval.parent(call('<-', xn, x)), silent = TRUE))
  invisible(x) 

or, since we don't care about the try-error object,

  on.exit(tryCatch(eval.parent(call('<-', xn, x)), error = function(e){}))
  invisible(x) 

Thoughts? @CarterButts ?

@krivit
Copy link
Member Author

krivit commented Nov 14, 2024

Alternatively, we could create a function that executes the pattern:

assign_in_place <- function(x, val = x){
  xn <- substitute(x)
  xnn <- eval.parent(call("substitute", xn))
  eval.parent(on.exit(tryCatch(
    eval.parent(call("<-", xnn, val), n = 2),
    error = identity
  )))
  invisible(val)
}

Then, a function can call it as the last thing and modify its argument in place:

f <- function(x){
  assign_in_place(x, x+1)
}

y <- 1
z <- 1

(f(z)) # Changed
#> [1] 2
z # Changed
#> [1] 2
(f(y)) # Changed
#> [1] 2
y # Changed
#> [1] 2
(f(z)) # Changed
#> [1] 3
z # Changed
#> [1] 3

(f(identity(z))) # Changed
#> [1] 4
z # Unchanged
#> [1] 3

Created on 2024-11-14 with reprex v2.1.1

@krivit
Copy link
Member Author

krivit commented Nov 15, 2024

A slightly more sophisticated version, that is robust to x being modified in place in its calling function.

modify_in_place <- function(x, value = x){
  xn <- substitute(x) # Grab the name of the argument to be updated.
  xnn <- match.call(sys.function(-1), sys.call(-1))[[xn]] # Grab the expression that was passed into its argument.

  eval.parent(on.exit( # As the calling function exits...
    tryCatch( # try to...
    eval.parent(call("<-", xnn, value), n = 2), # Assign to the expression in the caller's calling environment the expression,
    error = identity # and do nothing if it fails.
    )))

  invisible(value) # Return invisibly.
}

@CarterButts , thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant