Adr*_*uat 5 macros clojure land-of-lisp
我正在尝试将以下宏从lisp的土地转换为clojure:
(defmacro tag (name atts &body body)
`(progn (print-tag ',name
(list ,@(mapcar (lambda (x)
`(cons ',(car x) ,(cdr x)))
(pairs atts)))
nil)
,@body
(print-tag ',name nil t)))
Run Code Online (Sandbox Code Playgroud)
但我一直陷入需要更多评估水平的投注.例如,以下需要评估t#:
(defmacro tag [tname atts & body]
`(do (print-tag '~tname '[~@(map (fn [[h# t#]] [h# t#]) (pair atts))] nil)
~@body
(print-tag '~tname nil true)))
Run Code Online (Sandbox Code Playgroud)
因为它产生如下东西:
(tag mytag [color 'blue size 'big])
<mytag color="(quote blue)" size="(quote big)"><\mytag>
Run Code Online (Sandbox Code Playgroud)
我希望评估属性的位置.如果我在上面使用"(eval t#)",我就会犯这样的问题:
(defn mytag [col] (tag mytag [colour col]))
java.lang.UnsupportedOperationException: Can't eval locals (NO_SOURCE_FILE:1)
Run Code Online (Sandbox Code Playgroud)
有什么建议?
为什么在Clojure中似乎发生了一个较低级别的评估?
支持功能的定义:
;note doesn't handle nils because I'm dumb
(defn pair [init-lst]
(loop [lst init-lst item nil pairs []]
(if (empty? lst)
pairs
(if item
(recur (rest lst) nil (conj pairs [item (first lst)]))
(recur (rest lst) (first lst) pairs)))))
(defn print-tag [name alst closing]
(print "<")
(when closing
(print "\\"))
(print name)
(doall
(map (fn [[h t]]
(printf " %s=\"%s\"" h t))
alst))
(print ">"))
Run Code Online (Sandbox Code Playgroud)
(出于某种原因,我没有以与书相同的方式执行配对功能,这意味着它无法正确处理nils)
Clojure 的定义tag引用了属性映射中的所有内容,而 common Lisp 版本仅引用了名称。这是问题的直接根源 - 如果您只是将 放在'矢量/地图前面,然后摆弄 来map引用第一个元素,那么您可能会没事。
然而,虽然移植可能是一个很好的练习,但这段代码并不是按照 Clojure 方式编写的:打印是一个令人讨厌的副作用,使得很难使用 print-tag 来做任何有意义的事情;返回一个字符串会好得多。
(defmacro tag [name attrs & body]
`(str "<"
(clojure.string/join " "
['~name
~@(for [[name val] (partition 2 attrs)]
`(str '~name "=\"" ~val "\""))])
">"
~@body
"</" '~name ">"))
user> (tag head [foo (+ 1 2)] "TEST" (tag sample []))
"<head foo=\"3\">TEST<sample></sample></head>"
Run Code Online (Sandbox Code Playgroud)
当然,由于顺序并不重要,因此使用映射而不是向量对于属性来说更好。这也意味着您可以删除(partition 2...),因为地图的顺序视图已经成对出现。
一旦我们走到这一步,就会发现已经有很多方法可以将 XML 表示为 Clojure 数据结构,所以我永远不会在实际应用程序中使用上面的代码。如果您想真正使用 XML,请查看Hiccup、prxml或data.xml中的任何一个。