
Tie::Array::Lazy - Lazy -- but mutable -- arrays.

$Id: Lazy.pm,v 0.1 2007/05/26 17:54:19 dankogai Exp dankogai $

use Tie::Array::Lazy;
# 0..Inf
tie my @a, 'Tie::Array::Lazy', [], sub{ $_[0]->index };
print @a[0..9]; # 0123456789
$a[1] = 'one';
print @a[0..9]; # 0one23456789
print "$_\n" for @a; # prints forever

Tie::Array::Lazy implements a lazy array, an array that generates the element on demand. It is a lot like a lazy list but unlike lazy lists seen in many functional languages like Haskell, lazy arrays are mutable so you can assign values to their elements.
The example below explains how it works.
tie my @a, 'Tie::Array::Lazy', [3,2,1,0], sub{ 1 };
my @r = splice @a, 1, 2, qw/two one/
# @r is (2,1); tied(@a)->array is [3,'two','one',0];
pop @a; # 0; tied(@a)->array is [3,'two','one'];
shift @a; # 3; tied(@a)->array is ['two','one'];
shift @a; # 'two'; tied(@a)->array is ['one'];
pop @a; # 'one; tied(@a)->array is [];
pop @a; # 1; tied(@a)->array is [];
@a[3] = 3 # tied(@a)->array is [1,1,1,3];
You can think lazy arrays as arrays that auto-fills.

None.

makes @array a lazy array with its initial state with arrayref and element generator code with coderef. Here is an exmaple;
The coderef is a code reference which $_[0] is the Tie::Array::Lazy object itself (tied(@array)) and $_[1] is the index.
In addition to methods that Tie::Array provides, the object has methods below:
The reference to the internal array which stores values either generated or assigned.
# Fibonacci array
tie my @a, 'Tie::Array::Lazy',
[1, 1],
sub{ $_[0]->array->[-2] + $_[0]->array->[-1] }
Shorthand for scalar @{ $self->array }.
# 0..Inf
tie my @a, 'Tie::Array::Lazy', [], sub{ $_[0]->index };
The reference to the code reference to generate the value needed. Whenever the value is needed, Tie::Array::Lazy invokes the code below;
$self->maker($self, $index);
Like Tie::Array, you can use this module as a base class. See Tie::Array::Lazier for details.

Dan Kogai, <dankogai at dan.co.jp>

Please report any bugs or feature requests to bug-tie-array-lazy at rt.cpan.org, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Tie-Array-Lazy. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.

You can find documentation for this module with the perldoc command.
perldoc Tie::Array::Lazy
You can also look for information at:

Nick Ing-Simmons for Tie::Array
Matsumoto Yukihiro (Matz) for teasing me into hacking this module.

Copyright 2007 Dan Kogai, all rights reserved.
This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.