Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elisp List Contains a Value

Tags:

emacs

elisp

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.

like image 917
Nathaniel Flath Avatar asked Sep 11 '09 04:09

Nathaniel Flath


People also ask

What is Association list give suitable example?

It is a list of cons cells called associations: the CAR of each cons cell is the key, and the CDR is the associated value. Here is an example of an alist. The key pine is associated with the value cones ; the key oak is associated with acorns ; and the key maple is associated with seeds .

How do you get the last element of a list in LISP?

Assuming this is about Common Lisp, there is a function last which returns a list containing the last item of a list. If you use this function with mapcan, which applies a given function to each element of a list and returns the concatenated results, you'll get what you want.

Is nil an atom in Lisp?

The symbol nil is an atom and is also a list; it is the only Lisp object that is both. This function returns t if object is a cons cell or nil .

What is SETQ in Emacs?

This special form is just like set except that the first argument is quoted automatically, so you don't need to type the quote mark yourself. Also, as an added convenience, setq permits you to set several different variables to different values, all in one expression.


2 Answers

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).

like image 99
freiksenet Avatar answered Oct 02 '22 01:10

freiksenet


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 
like image 22
Mirzhan Irkegulov Avatar answered Oct 02 '22 01:10

Mirzhan Irkegulov