Search code examples
clojuredestructuring

is there a way to write a clojure function that destructures a map and returns any portion of the map?


I would like to write a function that accepts a specific structure of a map and returns (prints out) any portion of the map I want. Is this possible?

I haven't been successful so far. The following below are the functions I wrote to print portion a, b and c of the map but i seem to be missing some logic in this whole thing.

The test map is {:nums {:test number?}}. My true goal is to return the test value i.e number? or whichever value the user wishes to test e.g symbol? or vector?. This is why I have chosen to use this method.

I wish to understand the logic that's why I have chosen to return all the parts of the map i.e a, b, c.

Thanks.

(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str a)))
  )
=> #'user/des
(des {:nums {:test number?}})
{:nums {:test #object[clojure.core$number_QMARK_ 0x1089d00e "clojure.core$number_QMARK_@1089d00e"]}}
=> nil


(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str b)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil



(defn des [mapp]
  (let [[a [b c]] [mapp]]
    (println (str c)))
  )
=> #'user/des
(des {:nums {:test number?}})

=> nil

Solution

  • (defn des [mapp] 
      (let [m mapp
              {x :nums y :vects z :syms} m
              {a :test} x
              {b :test} y
              {c :test} z
              ]
        (println x)
        (println y)
        (println z)
        (println a)
        (println b)
        (println c)
        )
      )
    => #'user/des
    
    (des {:nums {:test number?}})
    {:test #object[clojure.core$number_QMARK_ 0x48c86e76 clojure.core$number_QMARK_@48c86e76]}
    nil
    nil
    #object[clojure.core$number_QMARK_ 0x48c86e76 clojure.core$number_QMARK_@48c86e76]
    nil
    nil
    => nil
    
    (des {:nums {:test number?}, :vects {:test vector?} :syms {:test symbol?}})
    {:test #object[clojure.core$number_QMARK_ 0x48c86e76 clojure.core$number_QMARK_@48c86e76]}
    {:test #object[clojure.core$vector_QMARK___5399 0x17d504aa clojure.core$vector_QMARK___5399@17d504aa]}
    {:test #object[clojure.core$symbol_QMARK_ 0x4593ff34 clojure.core$symbol_QMARK_@4593ff34]}
    #object[clojure.core$number_QMARK_ 0x48c86e76 clojure.core$number_QMARK_@48c86e76]
    #object[clojure.core$vector_QMARK___5399 0x17d504aa clojure.core$vector_QMARK___5399@17d504aa]
    #object[clojure.core$symbol_QMARK_ 0x4593ff34 clojure.core$symbol_QMARK_@4593ff34]
    => nil