4
votes

I have a map of vectors, like this:

{2 ["a" "c" "b"], 1 ["z" "y" "x"]}

I want to get a map that is sorted by keys, and then each corresponding vector is also sorted, like this:

{1 ["x" "y" "z"], 2 ["a" "b" "c"]}

I know I can sort by keys by doing (into (sorted-map) themap), and I know that I can supply a transducer to into, but I'm coming up short as to exactly how the transducer should look. Here's a transducer I've tried:

(defn xform [entry]
  (vector (first entry) (vec (sort (second entry)))))

However, when I try to apply it to my map, I get this exception:

java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.core$conj__4345

How can I get this to work? Is there a better way then using into with a transducer?

1
You almost got it. You just missed using the map function to create a map transducer. (map xform), though you shouldn't call this function an xform since it's not a transducer yet but just a function.ClojureMostly

1 Answers

6
votes

Like this:

(into (sorted-map)
      (map (fn [[k v]] [k (vec (sort v))]))
      {2 ["a" "c" "b"], 1 ["z" "y" "x"]})