Add new function `ensure-list'

* doc/lispref/lists.texi (Building Lists): Document it.

* lisp/subr.el (ensure-list): New function.

* lisp/emacs-lisp/shortdoc.el (list): Mention it.
This commit is contained in:
Lars Ingebrigtsen 2021-09-21 20:30:57 +02:00
parent a08bb1f682
commit be4f858498
5 changed files with 35 additions and 0 deletions

View file

@ -679,6 +679,20 @@ list are in the same order as in @var{tree}.
@result{}(1 2 3 4 5 6 7)
@end example
@defun ensure-list object
Ensure that we have a list. If @var{object} is already a list, it is
returned. If @var{object} isn't a list, a one-element list containing
@var{object} is returned.
This is usually useful if you have a variable that may or may not be a
list, and you can then say, for instance:
@lisp
(dolist (elem (ensure-list foo))
(princ elem))
@end lisp
@end defun
@defun number-sequence from &optional to separation
This function returns a list of numbers starting with @var{from} and
incrementing by @var{separation}, and ending at or just before

View file

@ -3825,6 +3825,11 @@ This function works along the line of 'replace-regexp-in-string', but
it matches on fixed strings instead of regexps, and does not change
the global match state.
+++
** New function 'ensure-list'.
This function makes a list of its object if it's not a list already.
If it's already a list, the list is returned as is.
+++
** New function 'split-string-shell-command'.
This splits a shell command string into separate components,

View file

@ -495,6 +495,9 @@ There can be any number of :example/:result elements."
:eval (list 1 2 3))
(number-sequence
:eval (number-sequence 5 8))
(ensure-list
:eval (ensure-list "foo")
:eval (ensure-list '(1 2 3)))
"Operations on Lists"
(append
:eval (append '("foo" "bar") '("zot")))

View file

@ -6426,4 +6426,12 @@ This is intended for internal use only."
(:success t)
(json-unavailable nil))))
(defun ensure-list (object)
"Ensure that we have a list.
If OBJECT is already a list, OBJECT is returned. If it's
not a list, a one-element list containing OBJECT is returned."
(if (listp object)
object
(list object)))
;;; subr.el ends here

View file

@ -767,5 +767,10 @@ See https://debbugs.gnu.org/cgi/bugreport.cgi?bug=19350."
(should-not (equal dir default-directory))
(should (file-exists-p default-directory)))))
(ert-deftest test-ensure-list ()
(should (equal (ensure-list nil) nil))
(should (equal (ensure-list :foo) '(:foo)))
(should (equal (ensure-list '(1 2 3)) '(1 2 3))))
(provide 'subr-tests)
;;; subr-tests.el ends here