Elisp List Contains a Value
Asked Answered
H

3

51

How do you check, in elisp, if a list contains a value? so the following would return t:

(contains 3 '(1 2 3))

but

(contains 5 '(1 2 3))

would return nil.

Headstock answered 11/9, 2009 at 4:28 Comment(0)
A
85

The function you need is member

For example:

(member 3 '(1 2 3))

It will return the tail of list whose car is element. While this is not strictly t, any non-nil value is equivalent to true for a boolean operation. Also, member uses equal to test for equality, use memq for stricter equality (using eq).

Aerification answered 11/9, 2009 at 4:34 Comment(1)
For further details, see gnu.org/software/emacs/emacs-lisp-intro/html_node/…Kiley
G
8

freiksenet's answer is good and idiomatic. If you are using dash.el, you could also call function -contains?, which does exactly the same—checks if some list contains an element:

(-contains? '(1 2 3) 2) ; t
Gruchot answered 3/8, 2014 at 17:1 Comment(0)
O
1

And if you want to find an element by applying a function, there's a seq-find:

(seq-find (lambda (val) (= 3 val))
          '(1 2 3))
Orville answered 16/2 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.