common-lisp Iterating over a list


Example

One can iterate over a list using ~{ and ~} directives.

CL-USER> (format t "~{~a, ~}~%" '(1 2 3 4 5))
1, 2, 3, 4, 5, 

~^ can be used to escape if there are no more elements left.

CL-USER> (format t "~{~a~^, ~}~%" '(1 2 3 4 5))
1, 2, 3, 4, 5

A numeric argument can be given to ~{ to limit how many iterations can be done:

CL-USER> (format t "~3{~a~^, ~}~%" '(1 2 3 4 5))
1, 2, 3, 

~@{ will iterate over remaining arguments, instead of a list:

CL-USER> (format t "~a: ~@{~a~^, ~}~%" :foo 1 2 3 4 5)
FOO: 1, 2, 3, 4, 5

Sublists can be iterated over by using ~:{:

CL-USER> (format t "~:{(~a, ~a) ~}~%" '((1 2) (3 4) (5 6)))
(1, 2) (3, 4) (5, 6)