I am trying to write a generic serilization function in clojure. Something Like this
(def input-map {:Name "Ashwani" :Title "Dev"})
(defn serialize [input-map delimiter]
...rest of the code
)
Which when called
(serialize input-map ",") Produces
Ashwani,Dev
I have some thing as of now which needs specific keys of the map but does this
(defn serialize [input-map]
(map #(str (% :Name) "," (% :Title) "\n") input-map ) )
What I want to avoid is the hardcoding Name and title there. There must be some way to use reflection or something to accomplish this but unfortunately I dont know enough clojure to get this done.
(defn serialize [m sep] (apply str (concat (interpose sep (vals m)) ["\n"])))
Give this a shot:
(require 'clojure.string)
(defn serialize [m sep] (str (clojure.string/join sep (map (fn [[_ v]] v) m)) "\n"))
(def input-map {:Name "Ashwani" :Title "Dev"})
(serialize input-map ",")
yields
"Ashwani,Dev\n"
Not sure how idiomatic this is, but it should work for you.
Update: Julien's answer is way nicer than mine! vals
... how could I miss that :)
It is quit simple.
(str input-map)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With