Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize an input-map into string

Tags:

clojure

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.

like image 664
Ash Avatar asked Jul 13 '11 13:07

Ash


3 Answers

(defn serialize [m sep] (apply str (concat (interpose sep (vals m)) ["\n"])))
like image 145
Julien Chastang Avatar answered Nov 18 '22 15:11

Julien Chastang


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 :)

like image 23
overthink Avatar answered Nov 18 '22 13:11

overthink


It is quit simple.

(str input-map)
like image 4
Tinybit Avatar answered Nov 18 '22 13:11

Tinybit