3

To sort a vector in clojure

(sort [ 2 3 1 4])

returns a list (sorted)

(1 2 3 4)

I can turn it back into the vector by

(into [] (sort [ 2 3 1 4]))

which is kind of inconvenient.

But if I sort a map/dictionary in clojure

(sort {2 "" 3 "" 1 "" 4 ""})

the return

([1 ""] [2 ""] [3 ""] [4 ""])

How do I turn it back into a sorted map? Or is there a better sort function that keeps the type/shape of the input?

5
  • 1
    See stackoverflow.com/questions/1528632/… Commented Feb 18, 2016 at 23:02
  • not a dupe, but stackoverflow.com/q/1989301/599075 indicates that there isn't a great way Commented Feb 18, 2016 at 23:02
  • I was about to post an answer involving empty and into, but it turned out to be much less useful than I expected. Commented Feb 18, 2016 at 23:11
  • Perhaps something like (apply into ((juxt empty sort) coll)), doesn't seem very useful though. Commented Feb 18, 2016 at 23:23
  • 2
    btw, sort doesn't return a list, but an ArraySeq. (class (sort [2 3 1 4])) ;=> clojure.lang.ArraySeq, vs (class '(4 3 2 1)) ;=> clojure.lang.PersistentList. Clojure has lots of different collection data structures, but there are only a few collection delimiter characters available, so there are things that aren't lists but whose printed representations use parentheses. There are not many functions that return lists, I believe. list is an exception. :-) Commented Feb 19, 2016 at 5:09

1 Answer 1

3

I dont know of a general way to always keep the original type/shape.

In case of a sorted map, its important to know that a regular map in clojure has no order (at least nothing you can or should rely on). For that clojure has sorted-map. There is also a useful function sorted-map-by that allows you to specify your own ordering.

So, in your example:

(into (sorted-map)  {2 "" 3 "" 1 "" 4 ""})
;; {1 "", 2 "", 3 "", 4 ""}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.