dgkf / R

An experimental reimagining of R
https://dgkf.github.io/R
GNU General Public License v3.0
136 stars 5 forks source link

Use binary `?` operator as `try-else` #52

Open dgkf opened 1 year ago

dgkf commented 1 year ago

R's error propagation is already quite powerful! All expressions are evaluated as though they can fail, and their errors are reported up through the call stack.

However, R's error capture and recovery is a bit messier. Instead of throwing errors, many codebases resort to returning NULL or some other value of significance to indicate an error, which can be interpreted as a special case by the calling function. This seems to be a pattern that has arisen out of the clunky error handling.

Perhaps we can make code both more readable and more stable by introducing better error handling features:

f <- function() {
  x <- g(x) ? g_default()
  paste0(x, "World")
}

The R world has no shortage of infix operators floating around, so deciding to reuse the binary infix behavior of a symbol should be done cautiously to make the best use of the syntax.

sebffischer commented 3 weeks ago

I quite like this proposal but I am wondering whether there is a way to make this more generic. I think in R there are at least three type of objects that need to often be handled with special care, which are na, null and error.

Maybe one could add ?err ?na and ?null.

sebffischer commented 3 weeks ago

Maybe one could even make this extendible, i.e. the language supports to add something like

?na = function(x) {
  is_na(x)
}

This is already implementable in R using %?na% but ?na just looks nicer.