简体   繁体   English

Clojure中的make-keyword-map - 惯用语?

[英]make-keyword-map in Clojure - Idiomatic?

I have been writing some Clojure recently, and I found myself using the following pattern frequently enough: 我最近一直在写一些Clojure,我发现自己经常使用以下模式:

(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? 或者我做错了什么,并且缺少一些已经建立的模式来处理这类事情?

Note, that you can also replace all of: 注意,你也可以替换所有:

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

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: 如果你的let表达式彼此依赖,那么宏如何如此:

(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: 那样(make-keyword-map x (foo 1) y (bar 2) z (zoom x))扩展为:

(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. 不知道如何惯用的是,但它也为您节省了let ,相比原来的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM