2011-10-21

Emacs Lisp: Loop Thru a List with dolist

Emacs Lisp: Loop Thru a List

Learned 2 elisp functions: {“dolist”, “number-sequence”}.

“dolist” lets you loop over a list with a variable. Here's sample usage:

(dolist (x '(1 2 3)) (insert (number-to-string x))) ; inserts "123"

“number-sequence” just generates a list of numbers:

(number-sequence 3 8) ; ⇒ (3 4 5 6 7 8)

Both are parts of emacs 23, but they are implemented as lisp macros. (Call “describe-function” to see their doc and source code.)

Normally, you can loop with a “while”, but the “dolist” syntax is leaner.

I learned them from jcs's blog. See:

Jon is a expert in Common Lisp, Scheme Lisp, and C. He often give useful tips about emacs. Very well written.