Siaris
Simple Things
Syndicate: full/short
Siaris
Categories
General0
News2
Programming2
LanguageBits0
Perl50
Ruby10
VersionControl1
Misc1
Article Calendar
<= July, 2008
S M T W T F S
12345
6789101112
13141516171819
20212223242526
2728293031
Search this blog

Key links
External Blogs
Brought to you by ...
Ruby
1and1.com

Iterating Over the Fibonacci Numbers

Andrew L. Johnson (First published by ItWorld.com 2001-09-06)

Consider the Fibonacci numbers (0,1,1,2,3,5,8,13,21,34,…), where the next number is the sum of the previous two in the series. We could create a recursive routine to calculate these:

    #!/usr/bin/perl -w
    use strict;

    sub fib {
      my $n = shift;
      return $n if $n < 2;
      fib($n-1) + fib($n-2);
    }

    for(0..9) {
        print fib($_),"\n";
    }
    __END__

However, a problem with this approach is that sue to its recursive nature, the fib() routine must recalculate earlier numbers in the series every time it is called. One simple solution is to create a cache to store numbers in the series and have the function use those if they exist This is called Memoization and there is a Memoize module on CPAN (we discussed this module back in May 2001). This technique is a trade off between using more space (the cache) and gaining more speed.

If one only wishes to iterate through the series in order (perhaps with breaks to do other processing) then another solution is to create an iterator using a closure:

    #!/usr/bin/perl -w
    use strict;
    sub gen_fib {
        my($curr, $next) = (0,1);
        return sub {
            my $fib = $curr;
            ($curr, $next) = ($next, $curr + $next);
            return $fib;
        };
    }

    my $fib_stream1 = gen_fib();
    my $fib_stream2 = gen_fib();

    # print first 5 Fibonacci numbers from stream 1
    print "Stream One:";
    for(1..5){
        print $fib_stream1->(), ' ';
    }
    print "\n";

    # print first 10 from stream 2
    print "Stream Two:";
    for (1..10) {
        print $fib_stream2->(), ' ';
    }
    print "\n";

    # print next 5 from stream 1
    print "Stream One:";
    for(1..5){
        print $fib_stream1->(), ' ';
    }
    print "\n";
    __END__

Some advantages of this technique are that it only stores enough state to calculate the next number (without recursion) rather than all the previous numbers in the series as memoization does, and you can have more than one independent iterator (or stream) in the same program. Disadvantages are that it is only useful in cases where you actually want to iterate through the series — it is not useful for calculating the Nth Fibonacci number (which the recursive solution could be used for).

You do not have to iterate over mathematical functions, you can iterate over anything — it is possible to create an iterator that iterates over N arrays in n-tuples (ie, get the first item from each array, then the second, …). With an array of array refs as a table, this is analogous to iterating over the columns rather than the rows.

Subroutine References as Closures

Andrew L. Johnson (First published by ItWorld.com 2001-08-30)

A closure is a tricky kind of thing to explain, but not terribly hard to understand. The following may not meet with computer science approval as an explanation of closures, but the examples should provide enough hands-on exposure to grasp underlying concept.

The first thing we need to understand is that named subroutines are global by nature — that is, the subroutine name (identifier) lives in the package’s symbol table. However, they run within the lexical scope they were defined within:

    #!/usr/bin/perl -w
    use strict;

    {
        my $inc = 10;
        sub incr {
            print "$inc\n";
            $inc++;
        }
    }

    incr();
    incr();
    __END__

    prints:
        10
        11

In the above, $inc is lexically scoped within the block, and the subroutine (incr()) is defined within the same block. We can not refer to $inc after the block (scope) is finished, but we can call the subroutine and it runs in the scope it was defined in so it can still access $inc and change it.

A closure is simply an anonymous subroutine that is bound to the lexical scope it was defined within (rather like the above situation.

    #!/usr/bin/perl -w
    use strict;

    sub make_incr {
        my $inc = shift;
        return sub {print "$inc\n"; $inc++};
    }

    my $c1 = make_incr(10);
    my $c2 = make_incr(20);

    $c1->();
    $c2->();
    $c1->();
    $c2->();
    __END__
    prints:
        10
        20
        11
        21

Our make_incr() routine is a closure generator — it takes an argument and creates a new lexical variable. It then returns an anonymous subroutine that uses this same variable. Each time we call this routine a new lexical $inc is created and the anonymous subroutine refers to that particular copy of $inc. Each closure generated ($c1 and $c2) have their own private copies of $inc to work with. Essentially, they each can save information about their current state (in this case, what number they are currently at).

Here is another simple example (adapted from my book) where the closure itself also takes an argument:

    sub exclaim {
        my $prefix = shift;
        return sub {print "$prefix $_[0]!\n"};
    }

    my $batman = exclaim('Indeed');
    my $robin  = exclaim('Holy');

    $robin->('Mackerel');   # prints: Holy Mackerel!
    $batman->('Robin');     # prints: Indeed Robin!

Closures can be useful for creating callback routines and iterators. The above example of make_incr() creates very simple iterators that simply count up by ones from a given base number. However, you can create an iterator to iterate through more complex functions as well. Next week we will discuss using a closure as an iterator over the Fibonacci numbers.

*****

Passing Subroutine References

Andrew L. Johnson (First published by ItWorld.com 2001-08-23)

Last week we look at using subroutine references for creating a dispatch table, this week we will consider passing subroutine references as arguments to other subroutines.

The ability to pass subroutine references is a powerful feature. Any subroutine you write that takes arguments can be thought of a general routine and the arguments provide the specifics. For example, a subroutine that calculates the square root of a number is general, and the argument provides the specific number to calculate the square root from and return the result. Passing a subroutine reference is no different in that respect, but rather than passing something static like a number or a string, you can pass a definition of an action to take.

An excellent example is the File::Find module which defines the find() routine (we saw this module back in February). The find() routine is a general directory tree traversal subroutine whose first argument is a reference to a subroutine, followed by a list of directories to traverse. The find() routine traverses the listed directories and calls the subroutine reference for each directory entry found (it also provides a package global variable holding the current directory entry, for your subroutine to use). This gives the user of the module a very flexible means of accomplishing virtually any task involving directory traversal — because the user supplies the intended action, the find() routine itself need only worry about the vagaries of traversing directories and none of the logic of detecting certain files, removing files, renaming files, or whatever else the user wishes to do.

You already know how to create a reference to a named function, and how to call a function through its reference — there really isn’t anything else you need to know to write a subroutine that takes a subroutine reference as an argument. Let’s consider writing a reduce() routine in Perl (such a routine exists in the List::Util module on CPAN, which is implemented in C, but we will implement in Perl here).

A reduce() function takes a function reference as its first argument and then a list of values. It "reduces" the list by applying the passed function to the first two values, then to the result of that and the next value in turn. Thus, it could be used to easily produce sums of lists by supplying a function reference that simply adds two arguments together:

    #!/usr/bin/perl -w
    use strict;
    my @array = (1,2,3,4);

    my $sum = reduce(\&add,@array);
    print $sum;

    sub add {
        $_[0] + $_[1]
    }

    sub reduce {
        my $sref = shift;
        return @_ if @_ < 2;
        my $init = shift;
        for (@_) {
            $init = $sref->($init, $_);
        }
        return $init;
    }

We have taken the extra caution of simply returning the argument list without calling the sub reference if a list of only one element is passed to reduce().

The above produces a result of 10. Using the same reduce function we could produce the results of multiplying through the list, or dividing through the list, or any other action we created a function to do:

    sub product { $_[0] * $_[1] }
    sub divide  { $_[0] / $_[1] }

    my $product  = reduce(\&product, @array);
    my $division = reduce(\&divide,  @array);

We can avoid creating named subroutines by using anonymous subroutines (just like we can have anonymous arrays and hashes, we can have anonymous subroutines which are references to subroutines with no names). We create such a subroutine reference by using the ‘sub’ keyword followed immediately by the block of code (no name is specified):

    my $sref = sub{print "Hello World\n"};
    $sref->();

So now we can use reduce() as follows:

    my $sum      = reduce( sub{ $_[0] + $_[1] }, @array);
    my $product  = reduce( sub{ $_[0] * $_[1] }, @array);
    my $division = reduce( sub{ $_[0] / $_[1] }, @array);

We could shorten that further using prototypes, but that is beyond the scope of the present article.

*****

Subroutine References

Andrew L. Johnson (First published by ItWorld.com 2001-08-16)

We have used subroutine references a couple of times in previous articles, but we haven’t taken a look at them directly.

You can take a reference to an existing (named) subroutine using the backslash operator along the ampersand in the following manner:

    sub foo {
        print "This is foo\n";
    }

    my $sref = \&foo;

You can call the referenced routine by preceding the scalar holding it with an ampersand, or by using the dereference arrow and parentheses:

    &$sref();     # or:  &$sref('argument')
    $sref->();    # or:  $sref->('argument')

It is important to realize that you cannot take a reference to a subroutine and pass it arguments at the same time:

    my $sref = \&foo('argument');

What this actually does is return a reference to the return value of that function (using the given argument), which probably isn’t what you wanted.

But what are subroutine references good for? A couple of common uses are dispatch tables and passing routines as arguments to other routines — we will consider the first here. A dispatch table is simply a table (usually a hash) that allows you to select which routine to run. Consider a user interface that queries the user to enter a command to run:

    #!/usr/bin/perl -w
    use strict;

    sub this { print "You picked 'this'\n" }
    sub that { print "You picked 'that'\n" }
    sub quit { exit }

    print "Enter a command:\n";
    while (<STDIN>) {
        chomp(my $cmd = $_);
        if ($cmd eq 'this') {
            this();
        } elsif ($cmd eq 'that') {
            that();
        } elsif ($cmd eq 'quit' or $cmd eq 'exit') {
            quit();
        } else {
            print "Unrecognized command: $cmd\n";
        }
    }
    __END__

Now imagine that there are many more possible commands the user could enter and you can see that the program would grow quite large. Using a dispatch table simplifies all of the logic of the if/elsif statements into the datastructure:

    #!/usr/bin/perl -w
    use strict;

    sub this { print "You picked 'this'\n" }
    sub that { print "You picked 'that'\n" }
    sub quit { exit }

    my %dispatch = (
        this => \&this,
        that => \&that,
        quit => \&quit,
        exit => \&quit,
        );

    print "Enter a command:\n";
    while (<STDIN>) {
        chomp(my $cmd = $_);
        if ($dispatch{$cmd}) {
            $dispatch{$cmd}->();
        } else {
            print "Unrecognized command: $cmd\n";
        }
    }
    __END__

This program is actually a little longer, but it is simpler in design and simpler to maintain and update — adding new commands involves only defining a subroutine and adding another entry to the hash (we don’t have to add further elsif clauses as we would with the first example.

*****

Tieing Variables

Andrew L. Johnson (First published by ItWorld.com 2001-08-09)

We have seen tie() used in previous articles dealing with DBM files, but we haven’t really talked about what exactly tie() does, or how you can create your own tied classes.

Essentially, tie() allows you to associate a variable with a particular class. Special methods are defined in a tied class that are implicitly called whenever you access this variable. In the Digest::MD5 article (Feb 2001), we tied an ordinary hash to a Berkeley DBM file — thus our hash acted as a persistent database on disk. All the magic of storing and retrieving hash elements from the disk was encapsulated in the DB_File module and was automatically performed whenever we assigned to the hash or retrieved and element from the hash.

You can tie scalars, arrays, hashes, and filehandles by defining an appropriate tied class implementing the behavior you desire. A main difference between a tied class and an ordinary class is that you must use special names (in all caps) for the methods that will be magically called when accessing a variable.

For a concrete example, let’s say we want to have a variable that takes on a random value from a list each time we use it — we will call the class RandSelect (and thus define a module named RandSelect.pm). We want to use this variable as in the following example:

    #!/usr/bin/perl -w
    use strict;
    use RandSelect;

    tie my $rand, 'RandSelect', qw(andrew greg brad john);
    print "The first six random selections are:\n";
    print $rand, "\n" for 1..6;

Which might print out (in one particular run):

    The first six random selections are:
    andrew
    greg
    john
    john
    andrew
    brad

But first we need to create our tied class. Our class begins in the normal fashion:

    package RandSelect;
    use strict;

but things change after this. The constructor for a tied scalar variable class is called TIESCALAR, and its first argument (like class methods in general) will be the class name:

    sub TIESCALAR {
        my $class = shift;
        return bless [@_], $class;
    }

That’s the entire constructor: We grab the class name and then we return a blessed anonymous array containing the remaining arguments passed to the call to the tie() function. We also need to create the method that will be called when we retrieve the value of a tied variable (named FETCH), and the one that will be called when we assign to a tied variable (named STORE). Each of this is an ordinary method call that will receive the object itself as the first argument, and then any remaining arguments (if any).

Even though we’ve tied a scalar variable, our object is really an array reference, so that’s what we deal with when trying to fetch and store values:

    sub FETCH {
        my $self = shift;
        return $self->[rand @$self];
    }

    sub STORE {
        my $self = shift;
        @$self = @{shift()};
    }
    1;
    __END__

Our FETCH routine merely returns a random element from the array reference, and the STORE routine expects an array reference and stores a copy of it in the object. We finish off our module with a single statement returning a true value (just ‘1;’) and that completes the entire tied scalar class. (we really should provide some error checking to ensure an array reference is passed to STORE, but that is an exercise for the reader).

There is already a module on CPAN (Tie::Pick) that is similar to the above but removes each element as it is chosen from the list.

Tieing a scalar is the simplest kind of tied variable to create, there are many more methods that you need to define for tieing arrays and hashes. Further information on tie and creating tied classes can be found in the following Perl documentation pages:

    perldoc -f tie
    perldoc perltie
    perldoc Tie::Scalar
    perldoc Tie::Array
    perldoc Tie::Hash
    perldoc Tie::Handle

One final note: There is a bug in Perl 5.6.1 that sometimes causes a tied variable to be accessed twice when it is interpolated — that is why in the example above I used ‘print $rand, "\n"’ instead of the simpler ‘print "$rand\n"’. This bug should be fixed in 5.6.2.

*****