Emacs Lisp: replacing dolist with mapcar and dotimes with mapc

In my opinion working with while instead of dolist is much more comfortable. Here is one example function:

(defun cf-tab-delete-marked ()
  (interactive)
  (dolist (id rcd-tabulated-marked-items)
    (when (yes-or-no-p (format "Are you sure to delete the ID: %d?" id))
      (cf-delete-contact id t))
    (rcd-tabulated-remove-marks)))

I was so much used to dolist and dotimes from Common Lisp and have been thinking in this way also while learning Emacs Lisp and have been using those macros for long time. Instead, I am now prone and like it more to use while instead of dolist:

(defun cf-tab-delete-marked ()
  (interactive)
  (while rcd-tabulated-marked-items
    (let ((id (pop rcd-tabulated-marked-items)))
      (when (yes-or-no-p (format "Are you sure to delete the ID: %d?" id))
    (cf-delete-contact id t))))
    (rcd-tabulated-remove-marks))

By using while and pop one removes item by item and processes it in a lop until the list rcd-tabulated-marked-items is completely empty.

Here is one more isolated example:

(let ((list '("Hello" "Hello there" "How are you")))
  (insert "\n") ;; inserts new line
  (while list
    (insert (pop list)) ;; inserts each item of the list
    (insert "\n")))
Hello
Hello there
How are you

On the other hand the dotimes macro may easily be replaced either sometimes with while by using a counter or by using mapc functions that iterates a function over a list.

Here is the function where I have been using dotimes:

(defun cf-prepare-helm-id-list (list)
    "Prepares the list of candidates for helm"
  (let ((new-list '())
    (times (length list)))
    (dotimes (nr times new-list)
      (let* ((item (elt list nr)))
    (push (cons item (format "%s" (string-cut-id item))) new-list)))))

and here is the same function where I have replaced it with mapc:

(defun cf-prepare-helm-id-list (list)
    "Prepares the list of candidates for helm"
  (let ((new-list '()))
    (mapc (lambda (i)
        (push (cons i (format "%s" (string-cut-id i))) new-list))
      list)
    new-list))

I don’t say that those functions are optimized. I find it easier to think with mapc and while as my thinking changed from Common Lisp to Emacs Lisp. And it is interesting phenomena.

Related hyperdocument tags

emacs-lisp emacs programming dolist mapcar

GNU Free Documentation License

Copyright © 2021-04-09 20:11:42.022413+02 by Jean Louis. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License”