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?

3

1 Answer 1

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))
3
  • 2
    Almost, you should drop the inner quotes. And you're missing a close parenthesis. Commented Feb 20, 2022 at 9:17
  • I've fixed those problems.
    – phils
    Commented Mar 23, 2022 at 2: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
    Commented Mar 24, 2022 at 5:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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