Search code examples
hy

Macro string Interpolation / How to unquote inside string?


I have a macro like:

(defmacro test [x] `"~x")

After running it expands to the following:

=> (test abc)
'~x'

Why doesn't it expand to 'abc'?

What is the correct method to unquote inside a string?


Solution

  • I'm confused why you expected this to work, and I'm unclear what you want. ~ in your example is in a string literal, so it's an ordinary string character, not the ~ operator, the same way that ((fn [x] "x") 5) returns "x" and not "5".

    If you want to stringify the model that you're passing into a macro, use str, like this:

    hy 1.0a1+114.g2abb33b1 using CPython(default) 3.8.6 on Linux
    => (defmacro test [x] (str x))
    <function test at 0x7fe0476144c0>
    => (test abc)
    "abc"