When I evaluate

(setq sample-list (list 'abc 'def))
(message "%s_suffix" sample-list)

Output is:

(abc def)_suffix

But I need to get:

abc_suffix def_suffix

How can I get the output?


It's unclear just what you want - return a list with elements abc_suffix and def_suffix? Print each of those? Show them in the echo area (message)? Return a string of those separated by a space?

;; Return a list with the suffix appended to each element.
(mapcar (lambda (ss) (format "%s_suffix" ss)) sample-list)
;; Print, with the suffix appended to each.
(dolist (ss  sample-list) (princ (format "%s_suffix" ss)))
;; Return the string "abc_suffix def_suffix".
(mapconcat (lambda (ss) (format "%s_suffix" ss)) sample-list " ")
;; Show message in echo area, with the two separated by a space.
  (mapconcat (lambda (ss) (format "%s_suffix" ss)) sample-list " "))
  • 1
    The list elements in the question are symbols, so (symbol-name ss) is needed (and then maybe intern depending, once again, on what the desired result happens to be).
    – phils
    Mar 18 '21 at 11:54
  • @phils: Right, thx.
    – Drew
    Mar 18 '21 at 17:10

An idiomatic way to achieve this via recursion:

(defun print-list-with-suffix (lst)
  (cl-labels ((rec (x)
                   (unless (null x)
                     (message "%s_suffix" (car x))
                     (rec (cdr x)))))
    (rec lst)))

(setq sample-list (list 'abc 'def))

(print-list-with-suffix sample-list)
  • Recursion isn't idiomatic in Elisp ;).
    – Basil
    Mar 18 '21 at 11:24
  • @Basil you're right. But it will be once native compilation is merged into the master branch; tail-call optimization ftw Mar 18 '21 at 17:50
  • That's true, but with several caveats: even after nativecomp is merged, it's not guaranteed to be present in any given Emacs configuration, and tail recursion elimination apparently only happens at speed 3, so these optimisations can not be considered part of the Elisp language. Having said that, Emacs 28 has in the meantime gained a limited form of TCO for self recursion that works regardless of non/byte/native compilation. See these recent emacs-devel threads: lists.gnu.org/r/emacs-devel/2021-03/msg00775.html lists.gnu.org/r/emacs-devel/2021-01/msg00566.html
    – Basil
    Mar 18 '21 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.