我如何编写带有变量的中缀宏?

问题描述 投票:0回答:1

我想编写一个宏,它获取一个向量作为包含绑定的第一个参数。第二个参数应该是计算。 例如:(中缀变量 [a 6] 3 + 5 * a)。有谁知道我如何编写这样的宏?我不知道如何评估第二个参数,因为可以有任意数量的参数。感谢您的帮助!

defmacro infix
  [& infixed]
  (cond
    (= (count infixed) 3) (list (nth infixed 1) (nth infixed 0) (nth infixed 2))
    (> (count infixed) 3) (let [[op1 val1 op2 & rest] infixed]
                             `(infix (infix ~op1 ~val1 ~op2) ~@rest))
    :else (throw (IllegalArgumentException. "This infix macro works only for 3 or more arguments"))))

(defmacro infix-variable
  [bindings & expr]
  `(let [~@bindings]
     (infix ~@expr)))

clojure
1个回答
0
投票

GitHub 上有一个库似乎一锤定音: https://github.com/rm-hull/infix

© www.soinside.com 2019 - 2024. All rights reserved.