Pyli/Iterators

From Jonathan Gardner's Tech Wiki
Jump to: navigation, search

Iterators

One of the core concepts in the language is that every expression is a vector. Well, not quite. Every expression is really an iterable.

  • Iterable: An object that has a default iterator associated with it (through iter) or an iterator itself.
  • Iterator: An object that supports the iterator interface, namely returns itself when iter is called, and returns the next value or raises stop-iter-error when next! is called.

Using an Iterator

To get an iterator, just call iter:

  • (iter object) => iterator Always returns an iterator, or signals a missing method condition.

Calling iter on an iterator will return the iterator itself, of course.

Calling next! on an iterator will change the iterator and return the current value. If it is out of values, it will signal stop-iter-error, which is an error.

  • stop-iter-error: Raised when an iteration is completely consumed.
  • (next! iterator): Returns the next value of the iterator or signals stop-iter-error.

All of the methods that take a vector as a parameter and visit the elements one at a time will take any iterable object. Although they might be enhanced to be more performant with vectors, they will still work.

Defining an Iterator

To create a new iterator, simply create a new class with appropriate initialization parameters. Define a method next! for that class. Make iter return itself. You may also want to add functionality if this is a default iterator to return an iterator for the appropriate object using iter, although you can define special methods.

flip-flop

The flip-flop function creates an iterator that will always return True until the condition is met, at which point it ceases.

(flip-flop cond-expression)

The cond-expression is evaluated in the calling environment every time next is called. When it is True, then that value is returned. When it is false, then StopIteration is raised.

With two parameters, it becomes a bi-stable flip-flop which never terminates.

(flip-flop when-true when-false)

The flip-flop starts in the True state, and can either be in the True or False states.

When next is called from the True state, it will evaluate the when-true expression. If true, then it returns True and remains in the True state, If False, it returns False and switches to the False state. The when-false expression is not evaluated (yet).

When next is called from the False state, it will evaluate the when-false expression. If true, then it returns True and switches to the True state. (The when-true expression is not evaluated.) Otherwise, it returns False and remains in the False state.

range

This returns an iterator that will go through the range of values.

(range)
(range from)
(range from to)
(range from to step)

comp

(I need a better name!)

This does like the python comprehension.

(comp &(x for x in y))
(comp &([x, y] for [x,y] in z))