开发者

How to access an element in a list?

开发者 https://www.devze.com 2023-03-31 16:16 出处:网络
I h开发者_运维知识库ave this list: (\"x\" \"y\" \"z\") How do I extract an element from the list? (In this case I\'m interested in the first element in the list, but I\'m looking for a general solu

I h开发者_运维知识库ave this list:

("x" "y" "z")

How do I extract an element from the list? (In this case I'm interested in the first element in the list, but I'm looking for a general solution.)


You really should read an intro to elisp or something before you try to use it. The Elisp manual which comes with Emacs in some distributions is quite good.

(nth 0 mylist)

https://www.gnu.org/software/emacs/manual/html_node/elisp/List-Elements.html


If you know the list position of the element, then use (nth 0 mylist), as @triplee indicated.

If you want to test element equality (in this case, string equality) then use this:

    (car (member "y" mylist))

(member "y" mylist) returns the sublist (tail) ("y" "z"), and car returns the first element of that sublist (car is the same as nth with 0 first arg).

If the string you want is not a member of the list, then member returns the empty list nil (aka ()), and car of that list returns nil. So member is both (a) a predicate for testing list membership (returns nil' for not present and non-nil` for present) and (b) a way to extract the first sublist (tail) that contains the element you seek.


Read subsections List Elements and Using Lists as Sets of section Lists of GNU Emacs Lisp Reference Manual. The manual is your friend, it's the first place you should look, when you have a question about Elisp. To access the manual inside Emacs, view it using Info system by pressing F1imelispEnter, or navigate around Info-mode manually.

If you write serious Elisp code, I recommend installing dash package, which has plenty of functions to query and transform lists. For example, if you want to find a first (or last) element that satisfies a predicate, use -first or -last:

(-first 'evenp '(1 2 3 4 5 6)) ; 2
(-last 'evenp '(1 2 3 4 5 6)) ; 6
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号