The format
function with its many control sequences is practically a programming language in its own right. (In fact, many Lispers would call it a domain-specific language, a concept we will revisit in Chapter 17.) And, like most programming languages, format
can loop through data. It does this using the ˜{
and ˜}
control sequences.
To achieve this looping, pass the format
function a control string containing ˜{
and ˜}
, and a list to iterate through. The part of the control string between the ˜{
and ˜}
sequences is treated almost like the body of a loop. It will be executed a number of times, depending on the length of the list that follows it. The format
function will iterate through this list, applying each of its items to the specified section of the control string.
For example, let’s create a list of animals that we can use for testing:
>(defparameter *animals* (loop repeat 10 collect (random-animal)))
*ANIMALS* >*animals*
("dog" "kangaroo" "walrus" "kangaroo" "kangaroo" "walrus" "kangaroo" "dog" "tick" "tick")
Now we use the ˜{ ˜}
control sequences to to loop through this list:
> (format t "˜{I see a ˜a! ˜}" *animals*)
I see a dog! I see a kangaroo! I see a walrus! I see a kangaroo! I see
a kangaroo! I see a walrus! I see a kangaroo!
I see a dog! I see a tick! I see a tick!
To produce this loop, we simply pass the single variable *animals*
, a list of items, to the format
function. The control string iterates through the list, constructing the sentence "I see a ˜a"
for each member of *animals*
.
A single iteration construct can also grab more than one item from the list, as in this example:
> (format t "˜{I see a ˜a... or was it a ˜a?˜%˜}" *animals*)
I see a dog... or was it a kangaroo?
I see a walrus... or was it a kangaroo?
I see a kangaroo... or was it a walrus?
I see a kangaroo... or was it a dog?
I see a tick... or was it a tick?
Here, we have two ˜a
control sequences within a single looping construct. Each ˜a
pulls a single animal from the list, so two animals print for every iteration of the loop.
18.221.179.220