hadley / strict

Make R a little bit stricter
235 stars 10 forks source link

Don't allow `1:length(vector)` #27

Open Dasonk opened 7 years ago

Dasonk commented 7 years ago

Strict produces an error when one uses something that results in 1:0. The goal here being to prevent cases where someone uses 1:length(x) which can produce 1:0 when x is empty.

It seems to me the strict package is intended to help catch errors before they actually occur. If that's the case then it should warn about any uses of code that looks like 1:length(x) regardless of if it produces 1:0 or 1:10.

bbolker commented 7 years ago

make 'em use seq()! (this would also prevent the 1:n-1 == 0:(n-1) operator-precedence confusion ...)

torfason commented 4 years ago

make 'em use seq()! (this would also prevent the 1:n-1 == 0:(n-1) operator-precedence confusion ...)

seq() is no better:

seq(1,0)
#> [1] 1 0

I typically include a function I once created and called safer_seq() with a similar purpose as the strict functions:

function (from, to) 
{
    stopifnot(round(from) == from)
    stopifnot(round(to) == to)
    stopifnot(to >= from - 1)
    return(seq_len(1 + to - from) + from - 1)
}

Perhaps a strict_seq() should be added to strict?