繁体   English   中英

在Clojure中创建哈希映射是否有简短的形式?

[英]Is there a short form for creating hash-map in Clojure?

有没有一个简短的表格/宏可以让我做

(defn f [a b c]
  {a b c})

代替

(defn f [a b c]
  {:a a :b b :c c})

这显示了步骤。 删除实际使用的println:

(ns clj.core
  (:gen-class))

(defmacro hasher [& args] 
  (let [keywords      (map keyword args)
        values        args
        keyvals-list  (interleave keywords values)
  ]
    (println "keywords     "  keywords)
    (println "values       "  values)
    (println "keyvals-list "  keyvals-list)
    `(hash-map ~@keyvals-list)
  )
)

(def a 1)
(def b 2)
(println \newline "result: " (hasher a b))

> lein run
keywords      (:a :b)
values        (a b)
keyvals-list  (:a a :b b)

result:  {:b 2, :a 1}
(defmacro as-map [& syms]
  (zipmap (map keyword syms) syms))

用法:

(def a 42)
(def b :foo)

(as-map a b)
;;-> {:a 42 :b :foo}

请注意,要支持命名空间的关键字,如果要使其简短,则必须放弃对ns别名的支持:

(defmacro as-map [& syms]
  (zipmap (map keyword syms) (map (comp symbol name) syms)))

用法:

(def a 42)
(def b :foo)

(as-map example/a foo-of/b)
;;-> {:example/a 42 :foo-of/b :foo}

忠告:可能不是一个好主意,但在命名本地绑定时以节省可读性,表达性和灵活性为代价,为您节省了一些键盘操作。

这是我的老片段,我玩了一段时间。

(declare ^:private restructure*)

(defn ^:private restructure-1 [m [e k]]
  (cond
    (= :strs e) (reduce #(assoc %1 (name %2) %2) m k)
    (= :keys e) (reduce #(assoc %1 (keyword (namespace %2) (name %2)) %2) m k) 
    :else       (assoc m k (restructure* e))))

(defn ^:private restructure* [form]
  (if-not (map? form)
    form
    (as-> {} v
      (reduce restructure-1 v form)
      `(hash-map ~@(mapcat identity v)))))

(defmacro restructure [form]
  (restructure* form))

这个想法是,它提供了clojure.core / destructure的补充,它从解构形式到绑定,它捕获了绑定并构造了一个数据结构。

(let [x 1 y 2 z 3]
  (restructure {:keys [x y z]}))
;; => {:x 1 :y 2 :z 3}

暂无
暂无

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

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