Monday, August 17, 2009

Vector: Str and perl

Str and perl are two methods that I had to poke around a bit to figure out that I needed them, and how to define them, but are perfectly simple when defined. I started simply looking for how to overload say for Vector. I'd poked around for this a bit when I realized it was a perfectly stupid idea. I mean, that might be great for saying a single Vector, but it would be terrible for something like say "$c is the cross product of $a and $b".

Clearly, what I really wanted to do was overload ~ for Vector. I don't recall now whether I found what I was looking for in the specs or the Setting. Either way, here is the simple way to do this in the Vector class definition.

I don't quite understand the why our is needed here. I'm guessing it has something to do with explicitly declaring the return type (Str). Past that, the code is perfectly straightforward and elegant.

I spent some time thinking about making a new method that took a string representation of a Vector and parsed it, sort of a reverse of the Str method. But it was clear it could get very tricky with more complicated vectors -- for instance, a Vector of Vectors.

Then I realized that Perl 6 had a mechanism for outputting objects in a fashion they could be eval'ed in again: perl. Unfortunately, the default perl function just returns "Vector.new()" when called on a Vector object. According to #perl, this is intended to automatically do the right thing for cases like this sometime in the future. In the mean time, it is easily overloaded to something that works using the above code.

6 comments:

  1. I think to make proper perl method you should use some introspection functions to figure out name of the class. It can be some other class inheriting from Vector.

    ReplyDelete
  2. I had not considered that in the least. I do believe you're right, but I don't have the first idea where to start with that.

    ReplyDelete
  3. With help from jnthn@#perl6:
    $.WHAT.perl ~ ".new("...

    ReplyDelete
  4. or may be it's self.WHAT.perl ~ ...

    ReplyDelete
  5. Thanks! I actually scribbled down self.WHAT.perl on one of my terminal windows last night after seeing that thread on #perl6. I will try implementing it as soon as I have a test in place.

    ReplyDelete
  6. self.WHAT.perl worked beautifully. New code (and test) is pushed to github. Thanks!

    ReplyDelete