Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort a clojure set of maps?

Tags:

clojure

I have a set of maps something like this:

#{
  {:name "a" :value "b" ... more stuff here}
  {:name "b" :value "b" ... more stuff here}
  {:name "b" :value "b" ... more stuff here}
  {:name "a" :value "b" ... more stuff here}
  {:name "c" :value "b" ... more stuff here}
  {:name "a" :value "b" ... more stuff here}
}

: and I want to get to an ordered list, much like sql order-by name:

[
  {:name "a" :value "b" ... more stuff here}
  {:name "a" :value "b" ... more stuff here}
  {:name "a" :value "b" ... more stuff here}
  {:name "b" :value "b" ... more stuff here}
  {:name "b" :value "b" ... more stuff here}
  {:name "c" :value "b" ... more stuff here}
]

: how can I do this?

like image 463
yazz.com Avatar asked Mar 22 '11 17:03

yazz.com


People also ask

Are clojure maps ordered?

Clojure has three built-in map types: array maps, hash maps and sorted maps. Of these, hash maps and sorted maps are unordered, but array maps actually are ordered: this is explained in the data structures section of the official documentation on clojure.org.

How does map work in Clojure?

Maps are represented as alternating keys and values surrounded by { and } . When Clojure prints a map at the REPL, it will put `,'s between each key/value pair. These are purely used for readability - commas are treated as whitespace in Clojure. Feel free to use them in cases where they help you!


1 Answers

Function sort-by is what you're looking for:

(def s
  #{
    {:name "d" :value "b" }
    {:name "b" :value "b" }
    {:name "c" :value "b" }
    })
(sort-by :name s)
like image 138
Leonel Avatar answered Sep 22 '22 08:09

Leonel