find, find-if, find-if-not
find, find-if, find-if-not Function
Syntax:
find item sequence &key from-end test test-not start end key → element
find-if predicate sequence &key from-end start end key → element
find-if-not predicate sequence &key from-end start end key → element
Arguments and Values:
item—an object.
sequence—a proper sequence.
predicate—a designator for a function of one argument that returns a generalized boolean. from-end—a generalized boolean. The default is false.
test—a designator for a function of two arguments that returns a generalized boolean. test-not—a designator for a function of two arguments that returns a generalized boolean.
start, end—bounding index designators of sequence. The defaults for start and end are 0 and nil, respectively.
key—a designator for a function of one argument, or nil.
element—an element of the sequence, or nil.
Description:
find, find-if, and find-if-not each search for an element of the sequence bounded by start and end that satisfies the predicate predicate or that satisfies the test test or test-not, as appropriate.
If from-end is true, then the result is the rightmost element that satisfies the test.
If the sequence contains an element that satisfies the test, then the leftmost or rightmost sequence element, depending on from-end, is returned; otherwise nil is returned.
Examples:
(find #\d "here are some letters that can be looked at" :test #’char>)
→ #\Space
(find-if #’oddp ’(1 2 3 4 5) :end 3 :from-end t) → 3
(find-if-not #’complexp
’#(3.5 2 #C(1.0 0.0) #C(0.0 1.0))
:start 2) → NIL
Exceptional Situations:
Should be prepared to signal an error of type type-error if sequence is not a proper sequence.
See Also:
position, Section 17.2 (Rules about Test Functions), Section 3.6 (Traversal Rules and Side Effects)
Notes:
The :test-not argument is deprecated.
The function find-if-not is deprecated.
Expanded Reference: find, find-if, find-if-not
Finding an element by value
find searches for the first element in the sequence that matches the given item. Returns the element or NIL if not found.
(find 3 '(1 2 3 4 5))
=> 3
(find #\o "hello world")
=> #\o
(find 99 '(1 2 3))
=> NIL
Finding with a predicate using find-if
find-if returns the first element satisfying the predicate.
(find-if #'evenp '(1 3 5 4 7))
=> 4
(find-if #'alpha-char-p "123abc")
=> #\a
Searching from the end with :from-end
When :from-end is true, the rightmost matching element is returned.
(find-if #'evenp '(2 4 6 3 5) :from-end t)
=> 6
(find #\a "banana" :from-end t)
=> #\a
Using :key to search by a derived value
The :key function extracts the value to test from each element. The original element (not the key) is returned.
(find 'c '((a 1) (b 2) (c 3)) :key #'first)
=> (C 3)
(find-if #'plusp '((a -1) (b 0) (c 3)) :key #'second)
=> (C 3)
Restricting the search with :start and :end
(find-if #'oddp '(1 2 3 4 5) :start 2 :end 4)
=> 3