next up previous contents
Next: Iterating over two Up: CHAPTER.6: LIST PROCESSING Previous: Iterating on lists

Using for ... in ... do .... with lists

E.g., to add all the numbers in a list

    define addall(list) -> total;
        lvars x, total = 0;
        for x in list do
            x + total -> total
        endfor
    enddefine;

    addall([3 5 7 9]) =>
    ** 24

Using for inside [ ..... ]

We could use the FOR construct to define a procedure like delete. We use a local variable, say `x', to denote successive elements in a list. If the element is not the same as the item to be deleted, then leave the element on the stack. If all this is done inside the list brackets, using `%', then the items left on the stack will be made into a list.

    define new_delete(item, list) -> result;
        lvars x;
        [% for x in list do
             unless x = item then x /* left on stack */  endunless;
           endfor
        %] -> result
    enddefine;

    new_delete([a b], [[1 2] [3 4] [a b] [c d]]) =>
    ** [[1 2] [3 4] [c d]]


Aaron Sloman
Fri Jan 2 03:17:44 GMT 1998