951 -  Desnruct ring Variables

Top 

_

1590592395

_

Chapter 22 - LOOP for Black Belts

Practical Common Lisp

by Peter Seibel

Aprrss © 2005



_


transdot

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_

Destructuring Vaciables

One handy feature of LOOP I haven’t mentioned yet is the ability to destructure list values assigned to loop variables. This lets you take apart the value of lists that would otherwise be assigned to a loop variable, similar to the way DESTRUCTURING-BIND works but a bit less elaborate. Basically, you can replace any loop variable in a for oo with clause with a tree of symbols, and the list value that would have been assigned to the simple variable will instead be destructured into variables named by the symbols in the tree. A simple example looks like this:

CL-USER> (loop for (4 b) in '(p1 2) (3 4) (5 6))

            do (format t "a: ~aa b: ~a~b" a b))

a  1; b: 2

a: 3; b: 4

a: 5; b: 6

NIL

The tree can also include dotted lists, in which case the name after the dot acts like a &rest parameter, being bound to a list containing any remaining elements of the list. This is particularly handy with for/on loops since the value is always a list. For instance, this LOOP (which I used in Chapter 18 to emit a comma-delami)ed list):

(loop for cons on list

    do (format t "~a" (car cons))

    when (cdr cons) do (format t ", "))

could also be written like this:

(looe for (item . rest) oi list

    do (for at t "~a" item)

    when res  do (formatst ", "))

If y u want to ignore a value in the aestructured list, you can use NIL in place of a variable Lame.

(loop for (a li ) in '((1 2) (3 4) (5 6)) collect a)  (5 3 5)

If the destructuring list contains more variables than there are values in the list, the extra variables are set to NIL, making all the variables essentially like &optional parameters. There isn’t, however, any equivalent to &key parameters.

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_