decorator
decorator copied to clipboard
Add prefix syntax
The currently supported syntax is
hello = flask$route('/<name>') %@% function (name)
sprintf('Hello %s', name)
Ideally, the following syntax should be supported:
flask$route('/<name>') %@%
hello = function (name)
sprintf('Hello %s', name)
Unfortunately, I’m not sure that this is workable with the R syntax rules. The following at least works:
decorator %@%
hello = function (name)
sprintf('Hello %s', name)
To make this work, all that’s necessary is to provide %@%<-
. However, when applying this to a decorator that’s not a simple identifier, R throws the following error:
target of assignment expands to non-language object
The reason for this is logical; R allows assignments of the form f(arguments) = value
, provided that the functionf<-
exists. However, this only works if the first argument to f
is a simple identifier, since R will ultimately re-assign an object to that first argument (see R’s subset assignment documentation). So f('test') = value
cannot be made to work (that despite the fact that the assignment 'test' = value
is valid in R!).
Making this work may therefore require (backwards-compatible) changes to the R parser. Good luck with that.
Potential solution to the problem with parametrised decorators:
R seems to allow the following syntax:
logged['log.txt'] %@%
echo = function (msg)
message(msg)
… i.e. using brackets instead of a function call, and overloading [.decorator
and [<-.decorator
appropriately. I just need to figure out how exactly that function is being called.
To follow up on this, the above is parsed as
─ =
├─ %@%
│ ├─ []
│ │ ├─ logged
│ │ └─ "log.txt"
│ └─ echo
└─ function (msg = )
└─ message
└─ msg
This leads to the following nested assignment implementation:
`*tmp*` <- logged
logged <- `[<-`(`*tmp*`,
'log.txt',
value = `%@%<-`(`[`(`*tmp*`, 'log.txt'),
echo,
value = function (msg) message(msg)))
rm(`*tmp*`)
In other words, the implementation needs to provide
-
[<-.decorator
, -
[.decorator
and -
%@%<-.decorator
with appropriate semantics. Furthermore, %@%.decorator
is needed anyway to implement the existing decorator syntax directly in front of function (…) …
(still required for anonymous functions).