Feeds:
Posts
Comments

Archive for July, 2013

Perl “Not Generators”

Reading through the Generators page on the Python wiki inspired me to knock up something almost completely unlike generators using closures (something Perl has that Python hasn’t…) just for fun.

Edit: correction, thanks Bernhard.

Standard preamble…

use strict;
use warnings;

The count() not-generator

sub count
{
    my $cnt = -1;
    return sub {
        return ++$cnt;
    };
}

Helper function to make it easier to make not-generators

sub make_generator (&)
{
    my $sub = $_[0];
    my $finished = 0;
    return sub {
        return undef if $finished;
        local $_ = $sub->();
        $finished = 1 unless defined $_;
        return $_;
    };
}

Composing not-generators

sub compose (&$)
{
    my ($op, $generator) = @_;
    return sub {
        local $_ = $generator->();
        return undef unless defined $_;
        return $op->($_);
    };
}

Takewhile …

sub takewhile (&$)
{
    my ($match, $generator) = @_;
    return make_generator {
        local $_ = $generator->();
        return $match->($_) ? $_ : undef;
    };
}

Foreach not-generator

I have to implement my own looping of course.

sub generator_for (&$)
{
    my ($fn, $generator) = @_;
    while (defined(my $ret = $generator->())) {
        $fn->($ret);
    }
}

Whew. And finally, after all that I can do the squares thing.

my $squares = compose { $_ * $_ } count();
my $bounded_squares = takewhile { $_ < 100 } $squares;
generator_for { print @_, "\n" } $bounded_squares;

Read Full Post »

I finally got around to watching the Python keynote recommended by Steve. Two thirds of the “things we have that other people don’t have” is Python finally catching up with Perl features from 1995 and they were in other languages more than 10 years before that (is that ignorance or the Blub effect?). And we already have the rest in various libraries.

Oh well…

Read Full Post »

Stop me if you’ve heard this one:

A Perl programmer and a Python programmer walk into a bar.

Python dev says “why are you using Perl, Python is much clearer”

“What do you mean”, says Perl dev, “how is it clearer?”

“It’s obvious innit,” says Python dev. It’s cleaner and better It’s got, er, objects and stuff.

C/C++ integration aside, has anyone got anything more meaningful than “cleaner and better” ? I’m genuinely curious.

Read Full Post »

Follow

Get every new post delivered to your Inbox.