I have a list, and want to clear it with (setq slist '())
. But I only want to do this when the number of elements exceeds the value N
.
1 Answer
You can do it using this macro
(defmacro normalize-list(l n)
"empties the list L when its size reaches N"
`(if(>=(length ,l),n)(setq ,l '())))
Examples
(setq slist'(foo bar baz)) ;->(foo bar baz)
(normalize-list slist 2);->nil
slist ;->(foo bar baz)
(normalize-list slist 5);->nil
slist;->nil
-
1
-
The argument l (for the list) must not be evaluated. In case l is bound to '(foo bar baz) What would elisp (setq l'()) render if the symbol l is evaluated? And what about (length l) if the argument l is quoted ?– gigiairCommented Aug 19, 2022 at 15:04
-
yup, good point. I was not thinking clearly earlier. Commented Aug 19, 2022 at 20:23
(when (> N (length slist)) (setq slist nil))
. Check out the on-board introduction to emacs lisp:C-h R eintr
which will help you answer several of your recent questions.(setq slist '())
. Is(setq slist nil)
preferable for reading?(eq nil '())
is true, it doesn't matter which you use. I think the latter is less noisy.