[Rd] Support for user defined unary functions

Jim Hester james.f.hester at gmail.com
Thu Mar 16 15:24:14 CET 2017


R has long supported user defined binary (infix) functions, defined
with `%fun%`. A one line change [1] to R's grammar allows users to
define unary (prefix) functions in the same manner.

    `%chr%` <- function(x) as.character(x)
    `%identical%` <- function(x, y) identical(x, y)

    %chr% 100
    #> [1] "100"

    %chr% 100 %identical% "100"
    #> [1] TRUE

This seems a natural extension of the existing functionality and
requires only a minor change to the grammar. If this change seems
acceptable I am happy to provide a complete patch with suitable tests
and documentation.

[1]:
Index: src/main/gram.y
===================================================================
--- src/main/gram.y     (revision 72358)
+++ src/main/gram.y     (working copy)
@@ -357,6 +357,7 @@
        |       '+' expr %prec UMINUS           { $$ = xxunary($1,$2);
 setId( $$, @$); }
        |       '!' expr %prec UNOT             { $$ = xxunary($1,$2);
 setId( $$, @$); }
        |       '~' expr %prec TILDE            { $$ = xxunary($1,$2);
 setId( $$, @$); }
+       |       SPECIAL expr                    { $$ = xxunary($1,$2);
 setId( $$, @$); }
        |       '?' expr                        { $$ = xxunary($1,$2);
 setId( $$, @$); }

        |       expr ':'  expr                  { $$ =
xxbinary($2,$1,$3);      setId( $$, @$); }



More information about the R-devel mailing list