Next: , Previous: , Up: Lists   [Contents][Index]


7.6 Searching Lists

SRFI 1 procedure: find predicate list

Returns the first element in list for which predicate is true; returns #f if it doesn’t find such an element. Predicate must be a procedure of one argument.

(find even? '(3 1 4 1 5 9)) => 4

Note that find has an ambiguity in its lookup semantics—if find returns #f, you cannot tell (in general) if it found a #f element that satisfied predicate, or if it did not find any element at all. In many situations, this ambiguity cannot arise—either the list being searched is known not to contain any #f elements, or the list is guaranteed to have an element satisfying predicate. However, in cases where this ambiguity can arise, you should use find-tail instead of findfind-tail has no such ambiguity:

(cond ((find-tail pred lis)
        => (lambda (pair) …)) ; Handle (CAR PAIR)
      (else …)) ; Search failed.
SRFI 1 procedure: find-tail predicate list

Returns the first pair of list whose car satisfies predicate; returns #f if there’s no such pair. find-tail can be viewed as a general-predicate variant of memv.

standard procedure: memq object list
standard procedure: memv object list
standard procedure: member object list [compare]

These procedures return the first pair of list whose car is object; the returned pair is always one from which list is composed. If object does not occur in list, #f (n.b.: not the empty list) is returned. memq uses eq? to compare object with the elements of list, while memv uses eqv? and member uses compare, or equal? if compare is not supplied.7

(memq 'a '(a b c))                      ⇒ (a b c)
(memq 'b '(a b c))                      ⇒ (b c)
(memq 'a '(b c d))                      ⇒ #f
(memq (list 'a) '(b (a) c))             ⇒ #f
(member (list 'a) '(b (a) c))           ⇒ ((a) c)
(memq 101 '(100 101 102))               ⇒ unspecified
(memv 101 '(100 101 102))               ⇒ (101 102)
procedure: member-procedure predicate

Returns a procedure similar to memq, except that predicate, which must be an equivalence predicate, is used instead of eq?. This could be used to define memv as follows:

(define memv (member-procedure eqv?))

Footnotes

(7)

Although they are often used as predicates, memq, memv, and member do not have question marks in their names because they return useful values rather than just #t or #f.


Next: , Previous: , Up: Lists   [Contents][Index]