Skip to content

Declaring Types at Function Declaration

4 messages · IVO I WELCH, Duncan Murdoch, Henrik Bengtsson +1 more

#
Suggestion for Syntax Sugar:

Would it make sense to permit a simple way to allow a coder to document the function argument type?

f <- function( a:chr, b:data.frame, c:logi ) { ? }

presumably, what comes behind the ?:? should match what ?str? returns.

however, this need not be checked (except perhaps when a particular option is set).  catching errors as soon as possible makes code easier to debug and error messages clearer.

regards,

/iaw
#
On 2025-09-17 1:23 p.m., IVO I WELCH wrote:
We already have that:  the Rd file should give a text description, and 
it can be enforced by run-time tests in the function body, e.g.

  stopifnot(is.char(a), is.data.frame(b), is.logical(c))

What we don't have, and I don't think it would be feasible, is a way to 
do this at compile time.  In general variables and expressions in R 
don't have a fixed type that is known before they are evaluated.

Duncan Murdoch
#
There's also base::declare() in R (>= 4.4.0), which people are
exploring to programmatically declare types and other things
(https://github.com/HenrikBengtsson/Wishlist-for-R/issues/169). For
example, Tomasz Kalinowski uses it in 'quickr' for guiding the "R to
Fortran Transpiler" (https://github.com/t-kalinowski/quickr).

/Henrik

On Wed, Sep 17, 2025 at 10:38?AM Duncan Murdoch
<murdoch.duncan at gmail.com> wrote:
#
thanks.  (indeed, on this one, even I knew this can be done, and only at
runtime, of course, for all generality. ;-)).

My suggestion was only for a little syntactic sugar.  python has something
like it, too.