If I have a list, (“apple” “pear” “grape” “apricot”)
how do I create a new list with elements starting with the letter “a”? The new list will be: (“apple” “apricot”)
.
2 Answers
(seq-filter (apply-partially #'string-prefix-p "a")
'("apple" "pear" "grape" "apricot"))
If you have other similar questions, consult the seq
library, which provides some functions to manipulate sequence (including list).
-
2Thanks. This is what I was trying to do. Functions listed here gnu.org/software/emacs/manual/html_node/elisp/… is the
seq
librarary, right?– zeynelSep 21 at 7:48 -
2
-
1This is the answer, IMO. Corresponds exactly to the question posed: nothing missing or hidden.– DrewSep 21 at 15:17
For this specific use-case, you can also reuse a builtin function related to text completion named all-completions
:
(all-completions "a" '("apple" "pear" "grape" "apricot"))
;; => ("apple" "apricot")
For more details, see C-h f all-completions RET
.
-
-
2I think the accepted answer should mention
completion-regexp-list
, since it's not necessarily true thatall-completions
uses basic (i.e., plain prefix) completion. See Basic Completion.– DrewSep 21 at 15:06 -
2IOW, this answer really hides what's needed and how it might be solved by
all-completions
: filtering according to a prefix string.– DrewSep 21 at 15:12 -
@zeynel Yes, @shynur's answer is more general since
seq-filter
accepts arbitrary predicates as its first argument. Furthermore, it works on any type that satisfies the predicateseqp
, whereasall-completions
works on specific collection types (each with slightly different semantics) and is not extensible.– BasilSep 21 at 20:37 -
1@Basil: You're right, I shouldn't have mentioned
completion-regexp-list
, any more than argPREDICATE
- those are additional, optional tests made after matching. And yes,all-completions
does use only literal-prefix comparison to do the matching. I'll leave my mistaken comments, for info. And I've just filed Emacs bug #66147, to have the doc specify that matching for functions such asall-completions
means literal-prefix string matching.– DrewSep 21 at 21:50
awk
expression does).