0

I have written a Clojure function that can successfully sort a list of lists according to length frequency.

However, I don't like the way it is written. Does anyone have any suggestions for writing this in a different way?

(defn lfsort [n]
    (let [total (frequencies (map #(count %) n))]
      (sort #(< (total (count %1)) (total (count %2))) n)))

  (lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))
((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n))

Kind Regards, Ben.

1
  • 1
    What don't you like about how you wrote it? Is it too slow, or is there some other reason? Commented Dec 8, 2016 at 17:46

2 Answers 2

3
(defn lfsort [coll]
  (sort-by (comp (frequencies (map count coll))
                 count)
           coll))

How do we get here from your solution? First, note that (sort #(< (f %1) (f %2)) xs) is just (sort-by f xs). Then, since we only actually need to use the result of the frequencies call once, we can just inline it, and compose it with count to get our sort-by function.

You may or may not find this more readable than your posted solution; you can choose a middle ground by not inlining the frequencies call, but I think it's definitely better to use sort-by and comp than to spell out the sort lambda yourself.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi amalloy, perfect thankyou! It was the sort lambda that I didn't like.
1

Another way to do it is:

(defn lfsort [n]
  (->> n
       (group-by count)
       vals
       (sort-by count)
       (apply concat)))

For example,

(lfsort '((a b c) (d e) (f g h) (d e) (i j k l) (m n) (o)))
;((i j k l) (o) (a b c) (f g h) (d e) (d e) (m n))

I find this clearer. You may or may not.

1 Comment

Oddly enough, this solution has both the same number of tokens and the same number of parentheses as @amalloys's

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.