Extending suggestion for stopifnot
If all you care about is emulating static type checking, then you can also accomplish the same thing with lambda.r using type constraints on function definitions. e.g.
f(m) %::% matrix : matrix
f(m) %as% { m }
f(as.data.frame(matrix(rnorm(12),nrow=3)))
Error in UseFunction("f", ...) : No valid function for 'f(data.frame)'
f(1)
Error in UseFunction("f", ...) : No valid function for 'f(1)'
f
<function> [[1]] f(m) %::% matrix:matrix f(m) %as% ?
On Aug 20, 2013, at 4:36 PM, Peter Langfelder <peter.langfelder at gmail.com> wrote:
On Tue, Aug 20, 2013 at 11:41 AM, ivo welch <ivo.welch at anderson.ucla.edu> wrote:
I am using a variant of stopifnot a lot. can I suggest that base R
extends its functionality? I know how to do this for myself. this is
a suggestion for beginners and students. I don't think it would break
anything.
first, I think it would be more useful if it had an optional character
string, so users could write
stopifnot( is.matrix(m), "m is not a matrix" )
this would mean that stopifnot would have to detect whether the last
argument is a string. (I think stopifnot should have had only one
condition, and one should have used all() to test multiple conditions,
but this is a bridge that was already crossed.) upon failure,
stopifnot should print the character string. that's it.
A second enhancement would be a "smart string", which knows that
everything inside {{...}} should be evaluated.
stopifnot( is.matrix(m), "m is not a matrix, but a {{class(m)}}" )
I think using a function (in this case paste) is cleaner:
paste("m is not a matrix, but a", class(m))
It avoids adding a new convention ("evaluate everything between {{
}}") and has additional arguments.
my own programming variant looks even nicer,
is.matrix(m) %or% "m is not a matrix but a {{class(m)}}"
In R you can write it as
is.matrix(m) || stop("m is not a matrix but a ", class(m))
Examples:
m = 1
is.matrix(m) || stop("m is not a matrix but a ", class(m))
Error: m is not a matrix but a numeric
m = matrix(0,2,2)
is.matrix(m) || stop("m is not a matrix but a ", class(m))
[1] TRUE
But the construct
if (!is.matrix(m)) stop("m is not a matrix but a ", class(m))
is more readable for people not used to Pearl.
______________________________________________ R-devel at r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-devel