hyrule
hyrule copied to clipboard
defshadowed
From a discussion in hylang/hy#1346
(defmacro defshadowed [name args &rest body]
`(do
(defmacro ~name ~args ~@body)
(defn ~name ~args (~name ~@args))))
=> (defshadowed zerop [x]
... `(= ~x 0))
import hy
from hy import HyExpression, HyInteger, HySymbol
hy.macros.macro('zerop')((lambda x: HyExpression(((([] + [HySymbol('=')]) + [x]) + [HyInteger(0)]))))
def zerop(x):
return (x == 0)
None
=> (zerop 3) ; look ma, no function call!
(3 == 0)
False
=> (list (map zerop [0 1 2]))
list(map(zerop, [0, 1, 2]))
[True, False, False]
It's pretty limited, but sufficiently simple marcos could be shadowed this way in a single definition. This might be good enough for the type of things we'd want shadowed anyway.
Nice! I was imagining generating the macro from the function, but the other way around makes a lot more sense.
As for the limitations, in particular, defshadowed
doesn't support any &-syntax, like &rest
in its arguments list.
It only works on simple templates. The function definition expands it in advance, so any kind of conditional expansion won't work right. This limitation is more fundamental to the approach. The only general way around that is to macroexpand in the function at runtime and then eval it, which would perform poorly. But even that would choke on non-hygienic macros, and everything that broke let
.
There may be certain other special cases we could automate, like when a variadic macro could be implemented as a reduce over the binary case, like most of our operators. Our shadow
implementation is pretty repetitive.