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:

  1. a sorted map displayed in same way unsorted map in repl. seems convenient @ times inconvenient @ others.
  2. edn not have support sorted maps.
  3. 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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -