Published on Wed, 07/09/2014 - 10:45
How to sort a map by its keys (Clojure)
Just a short one; there isn't a straight forward method to sort an existing map by its keys and this may not be obvious to new comers.
(->> {:z 1 :a 10} (mapcat identity) (apply sorted-map))Short explanation: Using the threading macro ->> the first argument is passed as the last argument into the following expression thus (mapcat identity {:z 1 :a 10}); the returned value from this is then passed into the next expression (apply sorted-map [:a 10 : z 1]). Note: Apply is your friend here, and can be used in many situations to glue core functions together as apply (a macro) expands out the first argument and 'applies' it to the first argument e.g (sorted-map :a 10 :z 1)
Add new comment