From murdoch.duncan at gmail.com  Fri Mar 17 00:13:58 2017
From: murdoch.duncan at gmail.com (Duncan Murdoch)
Date: Thu, 16 Mar 2017 19:13:58 -0400
Subject: [Rd] Support for user defined unary functions
In-Reply-To: <CAD6tx95VZKQ00ESU9aqq_CBy7BNtX2_ANeaPryw+3W1RVL4vww@mail.gmail.com>
References: <CAD6tx95VZKQ00ESU9aqq_CBy7BNtX2_ANeaPryw+3W1RVL4vww@mail.gmail.com>
Message-ID: <9e2f5889-b9b8-f4ce-322f-86bcd3d077f8@gmail.com>

I don't have a positive or negative opinion on this yet, but I do have a 
question.  If I define both unary and binary operators with the same 
name (in different frames, presumably), what would happen?

Is "a %chr% b" a syntax error if unary %chr% is found first?  If both 
might be found, does "a %chr% %chr% b" mean "%chr%(a, %chr% b)", or is 
it a syntax error (like typing "a %chr%(%chr%(b))" would be)?

Duncan Murdoch




On 16/03/2017 10:24 AM, Jim Hester wrote:
> 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( $$, @$); }
>
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel
>



[Rd] Support for user defined unary functions
Duncan Murdoch