Search code examples
listelisp

How to use add-to-list on a list returned by function


I have a function that return a list. It may return a blank list or a number list. I would like to apply add-to-list to the return value. Is it possible?

     (defun return-list () body....)
     (setq test (add-to-list (return-list) 1) )

Solution

  • Function add-to-list operates on variables, not lists. E.g.:

    (defvar test (return-list))
    (add-to-list 'test 1)
    

    If you are adding to a list unconditionally, use macro push which operates on places:

    (push 1 test)
    

    In your case, however, you can do even simpler:

    (setq test (cons 1 (return-list)))
    

    If you want to add an element only if it is not there yet, use the macro cl-pushnew which operates on places too:

    (pushnew 1 test)
    ;; `test' is now (1)
    (pushnew 1 test)
    ;; `test' is still (1)