这是我的第一个Clojure宏 - 我是一个优步的人。
昨天我posted并改进了字符串模板替换功能。有人建议在编译时更换密钥。这是我的第一次尝试:
(defn replace-templates*
"Return a String with each occurrence of a substring of the form {key}
replaced with the corresponding value from a map parameter.
@param str the String in which to do the replacements
@param m a map of template->value
@thanks kotarak https://stackoverflow.com/questions/6112534/
follow-up-to-simple-string-template-replacement-in-scala-and-clojure"
[^String text m]
(let [builder (StringBuilder.)]
(loop [text text]
(cond
(zero? (count text))
(.toString builder)
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(.toString (.append builder text))
(if-let [[_ replacement] (find m (subs text 1 brace))]
(do
(.append builder replacement)
(recur (subs text (inc brace))))
(do
(.append builder "{")
(recur (subs text 1))))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(.toString (.append builder text))
(do
(.append builder (subs text 0 brace))
(recur (subs text brace)))))))))
(def foo* 42)
(def m {"foo" foo*})
(defmacro replace-templates
[text m]
(if (map? m)
`(str
~@(loop [text text acc []]
(cond
(zero? (count text))
acc
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(conj acc text)
(if-let [[_ replacement] (find m (subs text 1 brace))]
(recur (subs text (inc brace)) (conj acc replacement))
(recur (subs text 1) (conj acc "{")))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(conj acc text)
(recur (subs text brace) (conj acc (subs text 0 brace))))))))
`(replace-templates* ~text m)))
(macroexpand '(replace-templates "this is a {foo} test" {"foo" foo*}))
;=> (clojure.core/str "this is a " foo* " test")
(println (replace-templates "this is a {foo} test" {"foo" foo*}))
;=> this is a 42 test
(macroexpand '(replace-templates "this is a {foo} test" m))
;=> (user/replace-templates* "this is a {foo} test" user/m)
(println (replace-templates "this is a {foo} test" m))
;=> this is a 42 test
有没有更好的方法来编写这个宏?特别是,每个值的扩展版本都没有获得名称空间限定。
答案 0 :(得分:1)
我会尝试减少重复的东西。我调整了函数以使用累加器的宏方法,让replace-templates*
通过(apply str ...)
完成剩下的工作。通过这种方式,可以重用宏中的函数。
(defn extract-snippets
[^String text m]
(loop [text text
snippets []]
(cond
(zero? (count text))
snippets
(.startsWith text "{")
(let [brace (.indexOf text "}")]
(if (neg? brace)
(conj snippets text)
(if-let [[_ replacement] (find m (subs text 1 brace))]
(recur (subs text (inc brace)) (conj snippets replacement))
(recur (subs text 1) (conj snippets \{)))))
:else
(let [brace (.indexOf text "{")]
(if (neg? brace)
(conj snippets text)
(recur (subs text brace) (conj snippets (subs text 0 brace))))))))
(defn replace-templates*
[text m]
(apply str (extract-snippets text m)))
(defmacro replace-templates
[text m]
(if (map? m)
`(apply str ~(extract-snippets text m))
`(replace-templates* ~text ~m)))
注意:在您的宏中,您没有取消引用m
。所以它只能起作用,因为你之前有过它。它不会与(let [m {"a" "b"}] (replace-templates "..." m))
。
答案 1 :(得分:0)
将(defn m {"foo" foo*})
更改为(def m {"foo" foo*})
,它似乎有效。