Dan Sugalski wrote:
> Plus I can see each being used more often if we extend it to be valid for
> sparse arrays, or used more under the hood with iterators and lazy lists
> and suchlike things. Each, when used on a sparse array, would presumably
> return a list of offset/value pairs of valid entries in the array. Keys
and
> values would also, presumably, be extended to work with them. On
non-sparse
> arrays too, I suppose, though the lack of holes in them doesn't give
> each/keys/values much benefit over other methods of accessing the data in
> an array.
>
How iterators should behave really depends on the type of list. Lazily
generated lists can either be recursively generated sequences:

  @first5PowersOf2 = (1.. ^prev_item * 2 : 5);   # (1,2,4,8,16)

or they can be directly generated:

  @first5PowersOf2 = (1: ^index ** 2 : 5);   # (1,2,4,8,16)

In the recursively generated version, iterators should only calculate the
next item, since a loop using the iterator might be broken out of. On the
other hand, any index of a directly generated list can be calculated
directly.

Some complexity is added when lazily generated or sparse lists are used to
slice other lists:

  @matrix = (1,3,4,
             2,6,7);
  @column1of3 = (1..10000:3);   # (1,4,7,...10000)
  $col_sum = reduce ^last + ^next, @matrix[@column1of3];  # 3

When lazily generated, recursively defined lists are used to slice a sparse
array, it starts to become more complex to just find out what indexes are
defined. In these cases it will be important to only calculate the minimal
number of elements (i.e. just the next when using an iterator, just the
accessed element when indexing directly, all with memoization as
appropriate).


Reply via email to