Clojure metaprogramming dynamically fetches a record (newbie!)

I have a group of records (ABC) that implement the P protocol.

I want to write a method that will select one of the post types, build it, and then call the method on it.

For example, if I have a list of records (def types '(A B C))

I want to do something like(->(first types) 1 2 3)

+3


source to share


1 answer


Well, functions are also values ​​and can be stored and retrieved from data structures. Thus, you should be able to simply save the constructor functions you want to select in a convenient format and use them from there. Something like:

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

      



or you can even skip the data structure entirely:

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

      

+1


source







All Articles