Perlesque Obtained Class Declarations

Yesterday I finished a feature for which Paweł Murias (pmurias) has been clamoring: class declarations in Perlesque.  Class declarations act similarly to class declarations in Perl 6:

class Individual {
  has int $x_chrom; # attributes can't have initializers yet, but it's a \smop\
  has int $y_chrom;
  has Individual $xx_parent;
  has Individual $xy_parent;
  has string $dna;
  has int $id;

  my int $indiv_id; # just a unique tag

  # this tier of the block acts as a "static initializer"
  #  for the class, and runs at "declaration-time" (when
  #  the class block is encountered as the "interpreter"
  #  evaluates the program (from the programmer's perspective),
  #  so any lexicals declared here act as "private static fields"
  #  or "class fields" would for a Java/C# class, since they
  #  are accessible from the method blocks like a normal
  #  closure.  Named subs can also be declared here.

  method conceive(Individual $mate --> Individual) {
    my $offspring = Individual.new();
    # do a bunch of somewhat randomized stuff with $mate.dna and self.dna
    $offspring.xx_parent = self; # The self keyword is like the "this" keyword in C#
    $offspring.xy_parent = $mate;
    $offspring.id = ($indiv_id += 1); # closure access to a "private static field"
    return $offspring;
my $indiv = Individual.new();

Basically this enables Java/C#-style programming in Perlesque, in addition to the (functional-style subsets of) JavaScript/Perl5 enabled last week.

What's next:
  • Class derivation (a small matter of programming, actually - the declarative functionality is already available in RunSharp - it merely needs exposed in Perlesque syntax).  This would enable Perlesque programs to use things like the PrototypeChain<TKey, TValue> class I wrote in C# as a base class for a Perlesque class.  PrototypeChain is a generalized edition of the hashes-with-inheritance Prototype PMC (which I thought existed in Parrot, but which I was apparently imagining, according to #perl6 on freenode).  Such a thing would be quite useful for implementing lexical "pads" at runtime in a non-optimized Perl 6 implementation (and in fact the Perlesque compiler does use PrototypeChain to keep track of the lexical scopes).
  • Custom constructors, which should behave similarly to Perl 6 custom constructors, except these will just be declared using method new (optional paramlist) { } instead of the meta-object-y-ultra-flexible way Perl 6 uses

No comments:

Post a Comment