Wednesday, August 12, 2009

Perl 6 Class: Vector

A few days ago I set out to create my first real Perl 6 class. Actually, that's not strictly accurate: it was actually my first real Perl class for any variety of Perl. I have a long background in C++ OO, but Perl 5's object syntax always scared me off. (Yes, I know there is Moose these days, but I didn't really learn about Moose's existence until after I was sold on Perl 6.)

At any rate, most of the Perl 6 class examples I have seen are actually class hierarchy examples: all that nonsense about how dogs, trees, and ducks fit together. My first attempt, on the other hand, is a pure math class, Vector, intended to be a useful component in building up more complex geometry objects rather than be something to be derived from.

I've put what I have up now at github. (Geez, I just typed "gitbug" -- hope that wasn't a significant Freudian slip!) I'll try to talk about it in detail over the next few days (and to keep on improving it, too). For now, let me give my quick impressions of working on a numeric class in Perl 6.

Most importantly: I love this! Except for new, the syntax is perfectly natural for me. (And new is easy enough to get by with.) Hyperoperators made it easier to define operators that work on Vectors of arbitrary dimension it is to do strictly 3D vectors in C++ or C#. Unicode lets me define operators that have always had to be functions in C++. Perl's flexibility means Vectors can be defined over any class with vaguely numeric properties, yet it's easier than even a non-templated version would be in C++. Etc, etc.

The only drawback I have found so far is a significant Rakudobug -- you cannot define an operator which uses any version of that operator internally. So you cannot define operator + on Vector in terms of operator + on the Vector's coordinates. This is really a significant drawback for doing this sort of thing; I have worked around it by coming up with fanciful Unicode characters instead of + and -.

But except for that bug, working with this class was a dream. Everything is easy and straightforward, and amazing things can be accomplished with very little work.

3 comments:

  1. Why all the capitalized method names?

    ReplyDelete
  2. That's been the standard (in C++) I've worked to for about sixteen years now. So it's purely habit. I didn't even think about it...

    ReplyDelete
  3. ++. Loved Perl 6 success stories like this.

    ReplyDelete