Piers,

On Oct 12, 2005, at 5:22 AM, Piers Cawley wrote:
We definitely have two instances of A since, B.isa(::A). We also have
a fragile implementation of count.

:)

Sorry, I purposefully made it a kludge as that is usually the way the example is shown in most tutorials about class methods.


  class A {
    our %.count_of

    method count (Class $c:) { %.count_of{$c} }

    method BUILD {
      $class = ($?SELF.class)

      @countable_ancestors = $class.ancestors.uniq.grep :{.isa(::A)}

You can use the MRO here, which is an already linearized list of the inheritance tree (in C3 order) with all duplicates removed.


      for $class, [EMAIL PROTECTED] -> $c { %.count_of{$c}++ }
    }

Where we're assuming I've got the syntax of 'for' right, and that
'ancestors' is a class method that returns all of a class's
ancestors. This might not work too well in the face of a dynamic
inheritance tree, but it should be possible to work around. Something
like this might work:

   Class A {
     our %.instance_count_of

     method count (Class $c: ?$with_descendents = undef) {
       my @interesting_classes = $c;
       if $with_descendents {
         push @interesting_classes, *($c.all_subclasses);
       }
       [+] %.instance_count_of(@interesting_classes)
     }

     method BUILD {
       %.instance_count_of($?SELF.class)
     }
   }

Where we're assuming that a class can find all its subclasses

--
Piers Cawley <[EMAIL PROTECTED]>
http://www.bofh.org.uk/



Reply via email to