Keeping It Simple (... and not being stupid)

I have never been a fan of Perl's operator overloading support, not only is the API kind of awkward, but the functionality is limited and fairly inflexible (at least compared to other languages like OCaml and Scala). But that said, I felt it was important to have some support for it in the new p5-mop.

As is my typical approach, I first took a look at how Perl 6 is doing it, which is based largely on compound method names that specify the operators as well as how they will be parsed, a simple example being infix:<+>. I decided to give this approach a try and see what I could do, after some fiddling around, I was able to get the following code to come together and work:

class Foo {
    has $val;

    method infix:<+> ($x) {
        $val + $x
    }
}

my $foo = Foo->new( val => 10 );

is($foo + 1, 11, '... got the right value');

I then took this over to #p5-mop to discuss the approach. I specifically asked Ricardo Signes (our fearless pumpking) what he thought, and while he seemed liked the syntax, he (through discussion) reminded me that one of the key goals of this project is keeping things simple. While this syntax was not terribly hard to parse using Devel::Declare, it was both new syntax and new MOP functionality, which means added complexity. So I decided to step back a bit and give it some thought.

Then it hit me, ... we already have Traits!

So I then set about adding in traits support for methods (something I had been planning to do already), wrote up an overload trait and added it to the core traits set. The result was that this code now works ...

class Foo {
    has $val;

    method add ($x) is overload('+')  {
        $val + $x
    }
}

my $foo = Foo->new( val => 10 );

is($foo + 1, 11, '... got the right value');

I am much happier with the end result, not only did we not introduce any new conceptual burdens, we actually made the existing ones more consistent because traits now work the same across classes, attributes and methods.

Horray for keeping it simple, and not being stupid! (thanks Rik)

3 Comments

I wonder if the p6 people have a reason for /not/ doing it that way.

Hooray for Wheelerian radical conservatism. :-)

Leave a comment

About Stevan Little

user-pic I am the original author of Moose and am (again) working on the p5-mop project to bring some of the core features of Moose into the core. I am also conducting a thought experiment called Moe to see what an Ultra Modern Perl 5 would look like.