typestar

sort-by & into in Clojure

A record crate sorted by year and by plays, then poured out with into.

(def crate
  [{:title "Blue Train" :year 1958 :plays 31}
   {:title "Kind of Blue" :year 1959 :plays 88}
   {:title "Maiden Voyage" :year 1965 :plays 12}])

;; sort uses compare's natural ordering on a plain collection
(println (sort [1965 1958 1959]) (sort ["rye" "ash" "elm"]))

;; sort-by takes a key fn, and a keyword is the usual one
(println (map :title (sort-by :year crate)))

;; (comp - :plays) negates the key, which flips the order
(println (map :title (sort-by (comp - :plays) crate)))

;; into pours one collection into another and keeps the target's type
(println (into [] (map :year crate))
         (into #{} [1 1 2 3])
         (into {} [[:a 1] [:b 2]]))

How it works

  1. (sort [1965 1958 1959]) uses compare's natural ordering on a plain collection.
  2. (sort-by :year crate) keys on a keyword, and (sort-by (comp - :plays) crate) negates the key to flip the order.
  3. into keeps the target's type, so (into #{} [1 1 2 3]) drops the duplicate and (into {} [[:a 1] [:b 2]]) builds a map.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
645
Tokens
121
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 104 seconds.

Type this snippet

Step 2 of 3 in Seq toolkit, step 17 of 27 in Language basics.

← Previous Next →