clojure programmatically namespace map keys
Asked Answered
C

2

7

I recently learned about namespaced maps in clojure. Very convenient, I was wondering what would be the idiomatic way of programmatically namespacing a map? Is there another syntax that I am not aware of?

  ;; works fine
  (def m #:prefix{:a 1 :b 2 :c 3})
  (:prefix/a m) ;; 1

  ;; how to programmatically prefix the map?
  (def m {:a 1 :b 2 :c 3})
  (prn #:prefix(:foo m))        ;; java.lang.RuntimeException: Unmatched delimiter: )
Cherianne answered 1/5, 2017 at 15:54 Comment(0)
S
14

This function will do what you want:

(defn map->nsmap
  [m n]
  (reduce-kv (fn [acc k v]
               (let [new-kw (if (and (keyword? k)
                                     (not (qualified-keyword? k)))
                              (keyword (str n) (name k))
                              k) ]
                 (assoc acc new-kw v)))
             {} m))

You can give it an actual namespace object:

(map->nsmap {:a 1 :b 2} *ns*)
=> #:user{:a 1, :b 2}

(map->nsmap {:a 1 :b 2} (create-ns 'my.new.ns))
=> #:my.new.ns{:a 1, :b 2}

Or give it a string for the namespace name:

(map->nsmap {:a 1 :b 2} "namespaces.are.great")
=> #:namespaces.are.great{:a 1, :b 2}

And it only alters keys that are non-qualified keywords, which matches the behavior of the #: macro:

(map->nsmap {:a 1, :foo/b 2, "dontalterme" 3, 4 42} "new-ns")
=> {:new-ns/a 1, :foo/b 2, "dontalterme" 3, 4 42}
Snazzy answered 1/5, 2017 at 16:40 Comment(0)
I
1

Here is another example inspired by https://clojuredocs.org/clojure.walk/postwalk#example-542692d7c026201cdc327122

(defn map->nsmap
"Apply the string n to the supplied structure m as a namespace."
 [m n]
 (clojure.walk/postwalk
 (fn [x]
   (if (keyword? x)
     (keyword n (name x))
     x))
  m))

Example:

(map->nsmap  {:my-ns/a 1 :my-ns/b 2 :my-ns/c 3} "your-ns") 

=> #:your-ns{:a 1, :b 2, :c 3}
Improvise answered 23/2, 2021 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.