GNU Info

Info Node: (emacs-lisp-intro.info)Sorting

(emacs-lisp-intro.info)Sorting


Next: Files List Prev: Prepare the data Up: Prepare the data
Enter node , (file) or (file)node

Sorting Lists
-------------

   Emacs contains a function to sort lists, called (as you might guess)
`sort'.  The `sort' function takes two arguments, the list to be
sorted, and a predicate that determines whether the first of two list
elements is "less" than the second.

   As we saw earlier (*note Using the Wrong Type Object as an Argument:
Wrong Type of Argument.), a predicate is a function that determines
whether some property is true or false.  The `sort' function will
reorder a list according to whatever property the predicate uses; this
means that `sort' can be used to sort non-numeric lists by non-numeric
criteria--it can, for example, alphabetize a list.

   The `<' function is used when sorting a numeric list.  For example,

     (sort '(4 8 21 17 33 7 21 7) '<)

produces this:

     (4 7 7 8 17 21 21 33)

(Note that in this example, both the arguments are quoted so that the
symbols are not evaluated before being passed to `sort' as arguments.)

   Sorting the list returned by the `recursive-lengths-list-many-files'
function is straightforward; it uses the `<' function:

     (sort
      (recursive-lengths-list-many-files
       '("../lisp/macros.el"
         "../lisp/mailalias.el"
         "../lisp/makesum.el"))
      '<

which produces:

     (85 86 116 122 154 176 179 265)

(Note that in this example, the first argument to `sort' is not quoted,
since the expression must be evaluated so as to produce the list that
is passed to `sort'.)


automatically generated by info2www version 1.2.2.9