3
我有一大堆的實現協議P.Clojure的元編程動態選擇記錄(初學者!)
我想寫這將選擇類型的記錄之一,構造它的方法記錄(ABC),然後調用它的方法。
舉例來說,如果我有記錄 (def types '(A B C))
我要像做(->(first types) 1 2 3)
我有一大堆的實現協議P.Clojure的元編程動態選擇記錄(初學者!)
我想寫這將選擇類型的記錄之一,構造它的方法記錄(ABC),然後調用它的方法。
舉例來說,如果我有記錄 (def types '(A B C))
我要像做(->(first types) 1 2 3)
好清單,功能也值,並可以存儲在從數據結構檢索。所以你應該能夠以一些方便的格式存儲你想從中選擇的構造函數,並從那裏使用它們。喜歡的東西:
(defrecord foo [x y])
(defrecord bar [x y z])
(def constructors [->foo ->bar])
((first constructors) 4 5) ;;=> #user.foo{:x 4, :y 5}
;;or
(apply (second constructors) [20 true :baz]) ;;=> #user.bar{:x 20, :y true, :z :baz}
(-> (second constructors) (apply '(59 -30 false))) ;;=> #user.bar{:x 59, :y -30, :z false}
或者你甚至可以完全跳過的數據結構:
(defn quxx [n a-map]
((if (< 25 n) map->foo map->bar) a-map))
(quxx 2 {:x 3 :y 9 :z -200}) ;;=> #user.bar{:x 3, :y 9, :z -200}
(quxx 29 {:x 3 :y 9 :z -200}) ;;=> #user.foo{:x 3, :y 9, :z -200}