Arthur Putnam
Arthur Putnam

Reputation: 1111

Lisp, do something for every element in a list

How do I perform a function on every element in a list? For example say I have a list:

(1 x q)

and I was to use my-function on 1, x, q. Is there a predefined function for this? Similarly to foreach in a "higher" level language? Or do I have to manually step through it using car and cdr?

Any help would be much appreciated!

Upvotes: 3

Views: 8619

Answers (2)

sds
sds

Reputation: 60064

If you want to construct a fresh list of results of my-function, use mapcar:

(mapcar #'my-function my-list)

If you do not want the results, use mapc or dolist or loop.

See also

  1. What's the best way to learn LISP?
  2. The #' in common lisp
  3. Why #' is used before lambda in Common Lisp?

Upvotes: 6

Svante
Svante

Reputation: 51531

Of course there is.

Look a the hyperspec symbol index and read about the following:

  • map, map-into
  • mapcar, mapcan, mapcon, mapc, mapl, maplist
  • dolist
  • loop: (loop :for element :in list #|...|#)

If you need the results as another list of the same length: map, map-into, mapcar, loop. If you want to do it by side effects: dolist, loop.

Upvotes: 4

Related Questions