Yesterday, I wrote about generating a 10 × 10 multiplication table in Emacs Lisp. The solution I gave involved using the dolist
macro with a list of the numbers 1–10 like this
(dolist (r '(1 2 3 4 5 6 7 8 9 10)) ...)
That’s a little contrived and obviously doesn’t scale well but I couldn’t find a better way. Fortunately jpkotta knew just what to do. He suggested using number-sequence
so that the solution becomes
(dolist (r (number-sequence 1 10)) (dolist (c (number-sequence 1 10)) (insert (format "%2d " (* r c)))) (insert "\n"))
As I said in the previous post, none of this is very important so it wouldn’t be worth the followup post except that number-sequence
is essentially like the Python range
function (number-sequence
includes its upper bound while range
doesn’t) so together dolist
and number-sequence
provide a nice Elisp idiom for operating on a sequence of numbers. Thus a construct such as
for x in range(i,j): do_something(x)
in Python could be rendered as
(dolist (x (number-sequence i j))
(do-something x))
in Emacs Lisp. That’s a handy thing to know and I thought it was worth a followup so that jpkotta’s wisdom didn’t get lost in the comments.