Next: , Previous: , Up: Prepare the data   [Contents][Index]


14.9.1 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 (see Using the Wrong Type Object as an 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:

(29 32 38 85 90 95 178 180 181 218 263 283 321 324 480)

(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.)

This page has generated for branch:work/add_lispintr, commit:65845cf60c073f2f3182d1d07483530e9bbe1d96 to check Japanese translation.