typed icon indicating copy to clipboard operation
typed copied to clipboard

Multiple types via "OR" operator

Open mpadge opened this issue 4 years ago • 1 comments

Placeholder to start discussion: The Q-language stuff is going to need a way of declaring multiple permissible input types:

Character() | Integer()
Data.frame(ncol = 2|3)

or even

Data.frame(ncol<10)

The Data.frame should be relatively straightforward, by changing strict waldo::compare for something more general, but am I right in understanding that the first is not possible at all? How difficult would it be to redefine | to function as an or operator on multiple calls to the native types?

mpadge avatar Oct 28 '21 17:10 mpadge

This would be done as a part of https://github.com/Q-language/proposal/issues/8

Re : Character() | Integer()

There's always a call to ? at the top of the tree so from there we can override | locally to evaluate ?'s arguments.

We'd need to rethink the structure of the "assertion factory" object returned by Character() though, since | needs to access the checks, error messages, and recombine them. But I think this rethinking is needed anyway.

Re : Data.frame(ncol = 2|3)

This syntax is ambiguous and I think it might bring issues ({data.table} did something like this and it leads to issues, I personally think it was a mistake), but we if we follow https://github.com/Q-language/proposal/issues/8 we might do :

# override Data.frame to extend it
Data.frame <- Data.frame[
  min_col = function(x,y) stopifnot(ncol(x) >= y), 
  max_col = function(x,y) stopifnot(ncol(x) <= y)]

Data.frame(min_col =2, max_col=3) ? x <- cars # instead of `Data.frame(ncol = 2|3) ? x <- cars`

# or 
Data.frame <- Data.frame[ncol = function(x,y) stopifnot(ncol(x) %in% y)]
Data.frame(ncol = 2:3) ? x <- cars

Data.frame(ncol<10) would be Data.frame(max_col=9) using the first way above.

The types that {typed} provides out of the box could include such restriction but users might easily define their own.

Here the stopifnot errors don't look so nice, and we don't use {waldo}, in reality we'd have prettier errors, and maybe wrappers to make nice messages easy to design.

moodymudskipper avatar Oct 29 '21 15:10 moodymudskipper