[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Style Question: mapcar vs. dolist
- Subject: Style Question: mapcar vs. dolist
- From: hal@si.no (Hallvard Tretteberg)
- Date: Mon, 24 May 1993 11:56:53 GMT
In article <cecil-220593204749@ksl-mac-79.stanford.edu>
cecil@camis.stanford.edu (Cecil Huang) writes:
Well, here's my question. In performing operations on list, I got into
the habit of doing things like
(mapcar #'(lambda (object) (some action on object)) list-of-objects)
Today, however, I discovered DOLIST. Presumably, I could do this instead:
(dolist (object list-of-objects) (some action on object))
So my questions are:
1. Are the above two forms always equivalent?
2. If so, when is it more stylistic to use DOLIST? To use MAPCAR?
I've written a style guide for (among others) choosing between
different lisp constructs, and the general idea is to use the most
specific construct. The difference between dolist and mapcar is
twofold:
1) mapcar construct a new list with the result of applying the lambda
argument to each of the items in the list, while dolist has an
explicit result form.
2) it is possible to return from a dolist, since it contains an
implicit NIL-block.
If you in your code don't need to stop the iteration by returning you
shouldn't use dolist. If you don't need the list of the results you
shouldn't use mapcar, either. If both these are true, the mapc
function will do: It is like mapcar but doesn't construct the list of
results but instead returns the list it iterates over, i.e. it is use
for side-effecting only. So, to print som objects use
(mapc #'print list-of-objects) instead of
(mapcar #'print list-of-objects) or
(dolist (object list-of-objects) (print object))
I would guess some people would agree with the general rule of using
the most specific construct, but at the same time would prefer using
dolist instead of mapc, especially if the body (or lambda) is big.
What do you feel yourself?
--
Hallvard Traetteberg
Dept. of Knowledge Based Systems
SINTEF SI (Center for Industrial Research)
Box 124 Blindern, 0314 Oslo 3
NORWAY
Tlf: +47 22 06 79 83 or +47 22 06 73 00
Fax: +47 22 06 73 50
Email: Hallvard.Tretteberg@si.sintef.no