How to translate this Clojure code to Hy, so it prints 2?
It doesn't need to be like Clojure, i just want to hide + and replace it with - in local environment.
(defmacro q [expr]
`(let ~'[+ (fn [x y] (- x y))]
~expr))
(print (q (+ 3 1)))
In Clojure it prints 2 (let creates a local environment).
In Hy it prints 4.
How to make Hy print 2 also, by replacing the + with - ?
I need those local environments because i am making a DSL.
This doesn't do what you expect in Hy because
+is a macro, and macro calls take precedence over function calls:Your options are:
Instead of
+, use a name doesn't have the same name as a core macro, likemy+or+2.Only use your new
+in contexts other than the head of anExpression(which is the only place Hy expands macro calls), such as(map + (range 10)).In
q, replace the symbol+in the input instead of just setting the variable+, as in something likeUse
defmacroto define a new macro named+. This is a bad idea because you lose access to the original+in this module, including in the expansions of macros you didn't write that expect+to have its usual meaning. Local macros are not yet implemented (#900).