What is the Scheme function for finding an item in a list?

I have a list of elements' (abc) and I want to find if (true or false) x in it, where x can be, for example, a or d. Is there a built-in function for this?

+5
source share
4 answers

If you need to compare using one of the assembly operators in equivalence, you can use , or , depending on whether you want to search for equality using , or, respectively. memqmemvmember eq?eqv?equal?

> (memq 'a '(a b c))
'(a b c)
> (memq 'b '(a b c))
'(b c)
> (memq 'x '(a b c))
#f

, , , . , , , #f , . - ( - #f), memq, memv member , , , if, cond, and or.

> (if (memq 'a '(a b c))
     "It there! :)"
     "It not... :(")
"It there! :)"

? , . eq? (, , memq) , ; ( ). , , , eq?, . equal? (, , member?) , , , equal?. eqv? eq? , ; , , eqv?, eq? ( - , , eq?)

> (eq? 'a 'a)
#t
> (eq? 'a 'b)
#f
> (eq? (list 'a 'b 'c) (list 'a 'b 'c))
#f
> (equal? (list 'a 'b 'c) (list 'a 'b 'c))
#t
> (eqv? (+ 1/2 1/3) (+ 1/2 1/3))
#t

( , undefined , , , , R 5 RS- , )

, , find find-tail SRFI-1:

> (find-tail? (lambda (x) (> x 3)) '(1 2 3 4 5 6))
'(4 5 6)
+21

:

> (cond ((member 'a '(a b c)) '#t) (else '#f))
#t
> (cond ((member 'd '(a b c)) '#t) (else '#f))
#f

, , , #f. true false cond.

+3

, , :

(define (occurrence x lst)
       (if (null? lst) 0    
            (if (equal? x (car lst))  (+ 1 (occurrence x (cdr lst)))
                                     (occurrence x (cdr lst)) 
            )
       )
) 

x . true false.

0

All Articles