0

How can I use dolist to repeat an operation for each item in a list?

I have a sequence of statements:

(put 'downcase-region 'disabled nil)
(put 'upcase-region 'disabled nil)
(put 'narrow-to-defun 'disabled nil)
(put 'narrow-to-region 'disabled nil)
(put 'narrow-to-page 'disabled nil)
(put 'set-goal-column 'disabled nil)

that I want to re-factor by putting each name into a list, then repeating the operation for each name.

So I think the dolist function can achieve this.

This fails:

(dolist (command
  (
   'downcase-region
   'upcase-region
   'narrow-to-defun
   'narrow-to-region
   'narrow-to-page
   'set-goal-column
   )
  (put command 'disabled nil)))

with an error

Invalid function: 'downcase-region

Why is that an “invalid function” in one instance but not the other?

How should that dolist be written to achieve the same effect as the first example?

Drew
  • 77,472
  • 10
  • 114
  • 243
bignose
  • 639
  • 3
  • 15

1 Answers1

0

an error

Invalid function: 'downcase-region

Why is that an “invalid function” in one instance but not the other?

The error is complaining that it's been asked to invoke a function, named 'downcase-region.

This is because the list ('downcase-region 'upcase-region 'narrow-to-defun …) is evaluated immediately; which attempts to invoke a function named 'downcase-region. Which doesn't exist.

Instead of evaluating the list immediately, the list needs to survive as-is as a value for the dolist function. You do this by quoting the list.

(dolist (command
  '(downcase-region
    upcase-region
    narrow-to-defun
    narrow-to-region
    narrow-to-page
    set-goal-column
    ))
  (put command 'disabled nil))
bignose
  • 639
  • 3
  • 15
  • 2
    Almost, you should drop the inner quotes. And you're missing a close parenthesis. – Lindydancer Feb 20 '22 at 09:17
  • I've fixed those problems. – phils Mar 23 '22 at 02:49
  • @bignose: Re: your "format code more readably" edit -- if you're not using the standard indentation that Emacs gives you, you're (a) going to unnecessary effort; and (b) going to end up with code that no one else finds readable. I strongly recommend you simply get accustomed to how everyone else (and Emacs) formats lisp -- you will consider it readable soon enough. – phils Mar 24 '22 at 05:07