2015-04-18 51 views

回答

1

好清單,功能也值,並可以存儲在從數據結構檢索。所以你應該能夠以一些方便的格式存儲你想從中選擇的構造函數,並從那裏使用它們。喜歡的東西:

(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}