Hi all,

I want to create a kind of bitvector object. Ideally, I'd like to inherit
from Array and then overload [],=, +,- etc.
I tried to overload the '+' operator, but I can't get it to work as a
method. Also, I'd like to overload the assignment operator.
Is that at all possible?
Below is my attempt, with the ideal solution and the received errors in
comments.

Any suggestions?

Thanks,

Wim

------
use v6;

my $vec=Register.new(dec=>7);
# my $vec=Register.new(7);
# or even better:
# my Register $vec=7;

say $vec.reg;
# say vec[]; # undefined!
# new() should calculate reg. But how?

say $vec.dec;
# say $vec;

$vec.write(29);
# $vec=29;

say $vec.read(2,4);
# say $vec[2..4]

say $vec.read(3);
# say $vec[3]

say $vec.add(5);
# say $vec+=5; # *** Cannot cast from VObject (MkObject {objType = (mkType
"Register") ... to Double (VNum)

# say $vec + 5; # *** No compatible subroutine found: "&dec"

#----
class Register {
   has $.reg;
   has $.dec;

   method write ($self: $n) {
       $self.dec= $n;
       $self.reg= int2vec($n);
   }

   method read ($self: $i,$j=$i) {
       return $self.reg[$i..$j];
   }

   method add ($n) {
       $.dec+=$n;
       $.reg = int2vec($.dec)
   }

# This doesn't work: *** Missing invocant parameters in '&infix:+': 0
received, 1 missing
#   method infix:<+> ($self: Int $n) {
#       $self.add($n);
#   }

   sub int2vec ($n,$v=[]) {
       if ($n > 1) {
           if ($n % 2) {
               int2vec(($n-1)/2,[1,@$v]);
           } else {
               int2vec($n/2,[0,@$v]);
           }
       } else {
           return [$n,@$v];
       }
   }
}

#sub infix:<+> (Register $self, Int $n) {
#    return $n+$self.dec;
#}

#sub infix:<+=> (Register $self, Int $n) {
#    $self.add($n);
#}

--
If it's pointless, what's the point?
If there is a point to it, what's the point?
(Tibor Fischer, "The Thought Gang")

Reply via email to