Daniel Wu
Daniel Wu

Reputation: 361

How to generate this expression in Clojure?

I am using lobos to create a set of tables:

(create
  (table :users
    (integer :id 20)
    (varchar :name 100)))

The schema of a table is kept in a seq:

([:integer :id 20] [:varchar :name 100])

How can I generate that expression with the seq? I find clojure.contrib/apply-macro may be used, but are there other ways?

Upvotes: 1

Views: 75

Answers (1)

Symfrog
Symfrog

Reputation: 3418

You can use the following macro:

(defmacro table-create [name coll]
  `(~'create
    (~'table ~name ~@(map (fn [r]
                            (let [[type c v] r]
                              (list (symbol (subs (str type) 1)) c v)))
                          coll))))

Here is a sample run:

(macroexpand-1 '(table-create :users ([:integer :id 20] [:varchar :name 100])))
;=>     (create
         (table :users
                (integer :id 20)
                (varchar :name 100)))

Upvotes: 2

Related Questions