Home > Perl6 > An Iterator that knows it’s previous and next value

An Iterator that knows it’s previous and next value

We basicly need a prefetching iterator. Building any iterator is quite easy with gather/take.

use v6;

my @a = 1..20;

sub prev_iterator_next (@list){
  my ($prev, $current, $next);

  my @foo = @list;
  $current = @foo.shift;
  $next = @foo.shift;

  gather loop {
    take ($prev, $current, $next);
    $prev = $current;
    $current = $next;
    $next = @foo.shift;
    take ($prev, $next, Any) if !@foo;
    last if !@foo;
  }
}

for prev_iterator_next(@a) -> $prev, $curr, $next {
  say ($prev, $curr, $next).perl;
}

Rakudo doesn’t implement proper iterators yet, so we have to retreat to build a copy of the list and shift one element at a time of the beginning. It’s not overly fast that way ofc.

Advertisements
Categories: Perl6
  1. August 12, 2010 at 19:40

    Rakudo *does* have proper iterators; but in general things work better if they’re hidden rather than exposed.

    For this particular example, perhaps something like…?

    sub prev_iter_next(*@list) {
    @list.unshift(Any);

    gather while @list > 1 {
    take @list[0,1,2];
    @list.shift;
    }
    }

    This avoids creating any extra arrays or copies of elements, and will be much more efficient than the one in the post (as well as properly lazy at all steps).

    Thanks!

    Pm

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: