sortedmap - Serializing sorted maps in Clojure / EDN? -
how can serialize , deserialize sorted map in clojure?
for example:
(sorted-map :a 1 :b 2 :c 3 :d 4 :e 5) {:a 1, :b 2, :c 3, :d 4, :e 5}
what i've noticed:
- a sorted map displayed in same way unsorted map in repl. seems convenient @ times inconvenient @ others.
- edn not have support sorted maps.
- clojure support custom tagged literals reader.
additional resources:
same question 2 usable answers: saving+reading sorted maps file in clojure.
a third answer set custom reader literals. you'd print sorted maps like
;; non-namespaced tags meant reserved #my.ns/sorted-map {:foo 1 :bar 2}
and use appropriate data function when reading (converting hash map sorted map). there's choice made whether wish deal custom comparators (which problem impossible solve in general, 1 can of course choose deal special cases).
clojure.edn/read
accepts optional opts
map may contain :reader
key; value @ key taken map specifying data readers use tags. see (doc clojure.edn/read)
details.
as printing, install custom method print-method
or use custom function printing sorted maps. i'd go latter solution -- implementing built-in protocols / multimethods built-in types not great idea in general, when seems reasonable in particular case requires care etc.; simpler use one's own function.
update:
demonstrating how reuse ipersistentmap
's print-method
impl cleanly, promised in comment on david's answer:
(def ^:private ipm-print-method (get (methods print-method) clojure.lang.ipersistentmap)) (defmethod print-method clojure.lang.persistenttreemap [o ^java.io.writer w] (.write w "#sorted/map ") (ipm-print-method o w))
with in place:
user=> (sorted-map :foo 1 :bar 2) #sorted/map {:bar 2, :foo 1}
Comments
Post a Comment