Stepping Through A List

CAR (first element of a list) and CDR (remainder of the list) can be used to step through a list one element at a time:

  1. Initially, set a variable LST to the list to be processed.

  2. If LST is NIL, quit. Otherwise,
    
    (SETQ TOP (CAR LST))  or (SETQ TOP (POP LST))
    (SETQ LST (CDR LST))
    

  3. Process the element TOP; go to step 2.

Such loops are so frequently used that a macro is provided for them:


(DOLIST (var list) code)
will bind var to successive elements of list and execute code for each element.

(DOLIST (NAME NAMELIST)
  (PRINT (SUBST NAME 'TARGET
                     '(DEAR MR TARGET))) )

Contents    Page-10    Prev    Next    Page+10    Index