Function: sort
sort is a function defined in fns.c.
Signature
(sort SEQ &key KEY LESSP REVERSE IN-PLACE)
Documentation
Sort SEQ, stably, and return the sorted sequence.
SEQ should be a list or vector. Optional arguments are specified as keyword/argument pairs. The following arguments are defined:
:key FUNC -- FUNC is a function that takes a single element from SEQ and
returns the key value to be used in comparison. If absent or nil,
identity is used.
:lessp FUNC -- FUNC is a function that takes two arguments and returns
non-nil if the first element should come before the second.
If absent or nil, value< is used.
:reverse BOOL -- if BOOL is non-nil, the sorting order implied by FUNC is
reversed. This does not affect stability: equal elements still retain
their order in the input sequence.
:in-place BOOL -- if BOOL is non-nil, SEQ is sorted in-place and returned.
Otherwise, a sorted copy of SEQ is returned and SEQ remains unmodified;
this is the default.
For compatibility, the calling convention (sort SEQ LESSP) can also be used; in this case, sorting is always done in-place.
Probably introduced at or before Emacs version 25.1.
Source Code
// Defined in /usr/src/emacs/src/fns.c
{
Lisp_Object seq = args[0];
Lisp_Object key = Qnil;
Lisp_Object lessp = Qnil;
bool inplace = false;
bool reverse = false;
if (nargs == 2)
{
/* old-style invocation without keywords */
lessp = args[1];
inplace = true;
}
else if ((nargs & 1) == 0)
error ("Invalid argument list");
else
for (ptrdiff_t i = 1; i < nargs - 1; i += 2)
{
if (EQ (args[i], QCkey))
key = args[i + 1];
else if (EQ (args[i], QClessp))
lessp = args[i + 1];
else if (EQ (args[i], QCin_place))
inplace = !NILP (args[i + 1]);
else if (EQ (args[i], QCreverse))
reverse = !NILP (args[i + 1]);
else
signal_error ("Invalid keyword argument", args[i]);
}
if (CONSP (seq))
return sort_list (seq, lessp, key, reverse, inplace);
else if (NILP (seq))
return seq;
else if (VECTORP (seq))
return sort_vector (inplace ? seq : Fcopy_sequence (seq),
lessp, key, reverse);
else
wrong_type_argument (Qlist_or_vector_p, seq);
}