Search code examples
functioncommon-lispbuilt-in

Functions that Search for Items


There are a number of sequence (and also list) functions in Common Lisp that search a given sequence or list with respect to an item. For example, (position item sequence) searches the given sequence for an element matching the item. Some other sequence searching functions taking an item include find, count, delete, and remove. Similar list searching functions include pushnew, member, adjoin, assoc, and rassoc.

In each case only one item is searched for at a time. But if you want to search for multiple items using these handy built-in functions, the easiest way is probably to put the function in a loop for each item. The drawback is that the sequence or list will be newly scanned for each item.

You can write your own function to scan the sequence or list once for all items, but this seems like it is more-or-less duplicating the effort that went into designing the built-in functions in the first place. I'm wondering why these functions were not designed at a higher level of abstraction to take multiple items? Wouldn't the default performance (and results) with one item be the same?


Solution

  • What you are looking for is the -if and -if-not versions of search functions. E.g., to find all teenagers in your database, you could do

    (remove-if-not (lambda (age) (<= 13 age 19)) people :key #'person-age)