Previous: Generators, Up: Drivers


2.1.5 Previous Values of Driver Variables

Often one would like to access the value of a variable on a previous iteration. iterate provides a special clause for accomplishing this.

— Clause: for pvar previous var &optional initially init back n

Sets pvar to the previous value of var, which should be a driver variable, a variable from another for... previous clause, or a variable established by a for... =, for... initially... then or for... first... then clause (see Variable Binding and Setting). Initially, pvar is given the value init (which defaults to nil). The init expression will be moved outside the loop body, so it should not depend on anything computed within the loop. pvar retains the value of init until var is set to its second value, at which point pvar is set to var's first value; and so on.

The argument n to back must be a constant, positive integer, and defaults to 1. It determines how many iterations back pvar should track var. For example, when n is 2, then pvar will be assigned var's first value when var is set to its third value.

A for... previous clause may occur after or before its associated driver clause. for... previous works with generators as well as ordinary drivers.

Example:

       (iter (for el in '(1 2 3 4))
             (for p-el previous el)
             (for pp-el previous p-el initially 0)
             (collect pp-el))
  

This evaluates to (0 0 1 2). It could have been written more economically as

       (iter (for el in '(1 2 3 4))
             (for pp-el previous el back 2 initially 0)
             (collect pp-el))