Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep the map order in Clojure?

Tags:

clojure

I define a map in my code like:

(def templates {:list1 {:create_time "create_time"
                        :recharge_amount "recharge"
                        :invest_amount "invest"
                        ;; something else
                        }
                :list2 {:create_time "ct"
                         ;; something else
                        }
                ;;something else 
                })

I want the map keep the order by what I am defined. How to solve it?

like image 978
savior Avatar asked Nov 16 '14 05:11

savior


1 Answers

If your data won't change, you can use array-map:

(def templates
  (array-map
    :list1 {}
    :list2 {}
    :list3 {}))

(seq templates)
;; => ([:list1 {}] [:list2 {}] [:list3 {}])

(keys templates)
;; => (:list1 :list2 :list3)

Why the constraint with constant data, you ask? Well, an array-map might turn into a hash-map after basically any modification operation (if its contents grow too big to offer efficient lookups).

Alternatively, if you're open to external dependencies you could see if amalloy/ordered fits your needs.

like image 183
xsc Avatar answered Nov 16 '22 23:11

xsc