make-keyword-map in Clojure - Idiomatic?

∥☆過路亽.° 提交于 2019-12-23 10:14:10

问题


I have been writing some Clojure recently, and I found myself using the following pattern frequently enough:

(let [x (bam)
      y (boom)]
  {:x x
   :y y})

So I went ahead and wrote the following macro:

(defmacro make-keyword-map [& syms]
  `(hash-map ~@(mapcat (fn [s] [(keyword (name s)) s]) syms)))

With that, code now looks like:

(let [x (bam)
      y (boom)]
  (make-keyword-map x y)

Would this sort of macro be considered idiomatic? Or am I doing something wrong, and missing some already established pattern to deal with something of this sort?


回答1:


Note, that you can also replace all of:

(let [x (bam) y (boom)] {:x x :y y})

with just:

{:x (bam) :y (boom)}

which will evaluate to the same thing.


If your let expressions depend on one another, then how about a macro like so:

(defmacro make-keyword-map [& let-body]
  (let [keywords-vals (flatten (map (juxt keyword identity)
                               (map first (partition 2 let-body))))]
    `(let ~(vec let-body)
       (hash-map ~@keywords-vals))))

that way (make-keyword-map x (foo 1) y (bar 2) z (zoom x)) expands to:

(clojure.core/let [x (foo 1) y (bar 2) z (zoom x)]
  (clojure.core/hash-map :x x :y y :z z))

So something like this would work:

user=> (defn foo [x] (+ x 1))
#'user/foo
user=> (defn bar [x] (* x 2))
#'user/bar
user=> (defn zoom [x] [(* x 100) "zoom!"])
#'user/zoom
user=> (make-keyword-map x (foo 1) y (bar 2) z (zoom x))
{:z [200 "zoom!"], :y 4, :x 2}

Not sure how idiomatic that is, but it also saves you a let, compared to your original example.



来源:https://stackoverflow.com/questions/20913319/make-keyword-map-in-clojure-idiomatic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!