2

I have this list:

(setq MYLIST '("J. Phys."
               "New. J. Phys." 
               "J. Phys. Soc. Jap."
               "Phys. Plasmas"))

How can I get a new list ordered by the decreasing length of the strings? :

("J. Phys. Soc. Jap."
 "New. J. Phys."
 "Phys. Plasmas"
 "J. Phys.")

ADDENDUM. It happens that when I try the DoMiNeLa10 answer on a 232 element list I get a 130 list. 102 of them goes lost (they are not duplicates). If you need my list as a file please tell me how can I share it.

You can find my list here: MYLIST.

3

See DoMiNeLa10's answer for the canonical answer.

On Emacs 25 and later, however, and if you don't care about sheer performance, there is a way to save yourself some typing:

(require 'seq)
(seq-sort-by #'length #'> MYLIST)

or

(seq-sort-by #'string-width #'> MYLIST)

should you care about displaying the strings.

  • Anyone care to explain the downvote? – Basil Feb 18 '18 at 16:15
  • (downvote not mine). Can you please take a look my edited part of the question? – Gabriele Nicolardi Feb 18 '18 at 20:32
  • @GabrieleNicolardi Have you tried using copy-sequence as I mention in my comment to DoMiNeLa10's answer? I.e. like so: pastebin.com/raw/70G6CeRG – Basil Feb 18 '18 at 20:36
  • @GabrieleNicolardi Otherwise, try using my suggestion which automatically does this for you. – Basil Feb 18 '18 at 20:36
  • @GabrieleNicolardi If either of these suggestions fix the issue, then you should consider reaccepting DoMiNeLa10's answer with the copy-sequence caveat. – Basil Feb 18 '18 at 20:38
3

You can write a function which uses sort and pass it a predicate that comares lengths:

(defun my-sort-decreasing-length (list)
  (sort list
        (lambda (a b)
          (> (length a) (length b)))))
  • 2
    Note that sort destructively modifies the list, so you should usually pass it through copy-sequence first. – Basil Feb 18 '18 at 15:04
  • 1
    What @Basil said. And if you are OK with the list-structure modification and you have a variable that points to the original list, and you want it to also point to the modified list, then you need to assign it to the result of using sort: (setq mylist (my-sort mylist)). – Drew Feb 18 '18 at 16:13
  • I cannot accept your answer because of an issue with long lists. Please see my edit to the question. – Gabriele Nicolardi Feb 18 '18 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.