我想知道如何在Clojure中,如果传递一个符号名称和一个向量,来替换所述项目。
例如,我想替换以下任何实例:
[:not :symbolName]
和
(not symbolName)
所以:
[ [:p] [:not :q] [:not :r] [r] ]
会成为:
[ [:p] (not q) (not r) [r] ]
任何帮助将不胜感激,提前多多关爱^_^
这很笼统。
(defn sym-replace [[x y] & syms]
(cond
(and x y (some #{x} syms)) (list (-> x name symbol) (-> y name symbol))
(and x y) [x y]
:else [x]))
例子:
(def my-vec [[:p] [:not :q] [:not :r] ['r] [:foo :bar]])
(map #(sym-replace % :not) my-vec)
;; ([:p] (not q) (not r) [r] [:foo :bar])
(map #(sym-replace % :foo) my-vec)
;; ([:p] [:not :q] [:not :r] [r] (foo bar))
(map #(sym-replace % :not :foo) my-vec)
;; ([:p] (not q) (not r) [r] (foo bar))
(use '[clojure.walk :only (prewalk)])
(defn match? [x]
(and (vector? x)
(= (first x) :not)
(keyword? (second x))))
(defn transform [x]
(map (comp symbol name) x))
(defn replac [p t x]
(prewalk #(if (p %) (t %) %) x))
(replac match? transform [[:p] [:not :q] [:not :r] '[r]])
=> [[:p] (not q) (not r) [r]]