Today's Programming Praxis problem didn't really interest me so I decided to go back and do an older one. The problem I'm going to work on today is one of sorting lists of lists. So, given a list that contains other lists you must sort it two ways. First, by the length of each inner list and second by the frequency of that length occurring. See the original post for an example. Given clojure's sort functions this shouldn't be too hard.
The first one is especially easy:
;;Hett's Problem 1.28 (def test-list [[:a :b :c] [:d :e] [:f :g :h] [:d :e] [:i :j :k :l] [:m :n] [:o]]) (defn sort-by-length [some-list] (sort-by count some-list))Just use the
sort-byfunction passing it the
countfunction. So for each inner list the
sort-byreceives it will sort by the value returned from applying
countto that inner list.
The second sort is a little harder but not by much:
(defn sort-by-length-freq [some-list] (let [freq-map (frequencies (map count test-list))] (sort-by (fn [l] (freq-map (count l))) some-list)))First we build a map that associates the count of each inner list with the number of times it occurs. So a count of 3 occurs twice, count of 2 occurs 3 times, count of 4 occurs once, and a count of 1 occurs once. We then use that to give
sort-bya function that looks up the occurrences based on the count. gist