让我们对其进行宏扩展(用于您的第二个宏)
(parse-cmd "SET 1 1" "SET" mysum "GET" println)
它扩展为:
(let [parts__31433__auto__ (str/split "SET 1 1" #" ")
cmd__31434__auto__ (first parts__31433__auto__)
args__31435__auto__ (into [] (rest parts__31433__auto__))
clauses__31436__auto__ (partition
2
2
("SET" mysum "GET" println))]
(case
cmd__31434__auto__
(mapcat
(fn [c__31437__auto__] [(nth c__31437__auto__ 0)
(seq
(concat
(list 'apply)
(list (nth c__31437__auto__ 1))
(list 'args__31432__auto__)))])
clauses__31436__auto__)))
这里有两个问题:
1)您生成此代码:("SET" mysum "GET" println),这显然会导致您的异常,因为“SET”不是函数
2) 你生成了错误的case 表达式,我看到你忘记取消引用拼接你的mapcat
让我们尝试解决这个问题:
首先取消引用mapcat;然后你可以将clauses移出你生成的let,因为它可以完全在编译时完成:
(defmacro parse-cmd [command & body]
(let [clauses (partition 2 2 body)]
`(let [parts# (str/split ~command #" ")
cmd# (first parts#)
args# (into [] (rest parts#))]
(case cmd#
~@(mapcat (fn [c] [(nth c 0) `(apply ~(nth c 1) args#)]) clauses)))))
现在让我们检查一下扩展:
(let [parts__31653__auto__ (str/split "SET 1 1" #" ")
cmd__31654__auto__ (first parts__31653__auto__)
args__31655__auto__ (into [] (rest parts__31653__auto__))]
(case
cmd__31654__auto__
"SET"
(apply mysum args__31652__auto__)
"GET"
(apply println args__31652__auto__)))
好的。看起来更好。让我们尝试运行它:
(parse-cmd "SET 1 1" "SET" mysum "GET" println)
我们现在有另一个错误:
CompilerException java.lang.RuntimeException: Unable to resolve symbol: args__31652__auto__ in this context, compiling:(*cider-repl ttask*:2893:12)
所以扩展也向我们展示了这一点:
args__31655__auto__ (into [] (rest parts__31653__auto__))
...
(apply mysum args__31652__auto__)
所以args# 这里有不同的符号。这是因为生成的符号名称的范围是一个语法引用。所以带有apply 的内部语法引用会生成新的。你应该使用gensym 来解决这个问题:
(defmacro parse-cmd [command & body]
(let [clauses (partition 2 2 body)
args-sym (gensym "args")]
`(let [parts# (str/split ~command #" ")
cmd# (first parts#)
~args-sym (into [] (rest parts#))]
(case cmd#
~@(mapcat (fn [c] [(nth c 0) `(apply ~(nth c 1) ~args-sym)]) clauses)))))
好的,现在应该可以正常工作了:
ttask.core> (parse-cmd "SET 1 1" "SET" mysum "GET" println)
2
ttask.core> (parse-cmd cmd "SET" mysum "GET" println)
2
太棒了!
我还建议您在 mapcat 函数中使用解构并引用 let,以使其更具可读性:
(defmacro parse-cmd [command & body]
(let [clauses (partition 2 2 body)
args-sym (gensym "args")]
`(let [[cmd# & ~args-sym] (str/split ~command #" ")]
(case cmd#
~@(mapcat (fn [[op fun]] [op `(apply ~fun ~args-sym)]) clauses)))))
但是,如果这不仅仅是编写宏的练习,那么您不应该为此使用宏,因为您在这里只传递字符串和函数引用,所以无论如何您都应该在运行时评估所有内容。
(defn parse-cmd-1 [command & body]
(let [[cmd & args] (str/split command #" ")
commands-map (apply hash-map body)]
(apply (commands-map cmd) args)))