The :KEY
parameter is included in some functions that ship with Common Lisp. All of the descriptions that I have found of them are unhelpful, and :KEY
is difficult to search in a search engine because the ":" is usually ignored.
How would it be used, for example, in the member
function which allows both :TEST
and :KEY
?
The :key
argument is documented, somewhat cryptically, in the introductory sections to the Sequences Library (Section 17) in the Common Lisp HyperSpec, under 17.2.1 Satisfying a Two-Argument Test as well as 17.2.2 Satisfying a One-Argument Test. This is because its behavior is consistent across the library.
Quite simply, :key
specifies the function which is applied to the elements of the sequence or sequences being processed. The return value of the function is used in place of those elements. In the terminology of some functional languages, this is called a "projection". The elements are projected through the key function. You can imagine that the default key function is identity
, if you don't supply this argument.
One important thing to understand is that in functions which accept some object argument and a sequence (for instance functions which search a sequence for the occurrence of an object), the key function is not applied to the input object; only to the elements of the sequence.
The second important thing is that :key
doesn't substitute for the item, only for the value which is used to identify the item. For instance, a function which searches for an item in a sequence will retrieve the original item from a sequence, even if the items of the sequence are projected to alternative keys via :key
. The value retrieved by the key function is only used for comparison.
E.g. if obj-list
is a list of objects which have a name accessible via a function called obj-name
, we might look for the object named "foo"
using (find "foo" obj-list :key #'obj-name)
. The function obj-name
is applied to each element, and its result is compared with the string "foo"
(to which the function isn't applied). If at least one object by that name exists in obj-list
, then the first such object is returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With