Can the type of a variable vary independenty of its value?

Consider the following:


my @a = (1,2,3);
my $b := @a;

@a and $b both refer to the same object. $b's object has methods such as PUSH, POP, etc, as does @a's.

So the type of the value (object) is the same in each case, but the variable's types are different.

The difference becomes very obvious when you start doing DWIM stuff.

Consider this code:

print @a + $b

This will evaluate each, in numeric context. To get at those numbers, Perl will translate this to something like

print @a.FETCHSIZE + $b.FETCHNUM

And will promptly get a run-time error for the latter (maybe just a warning). The underlying object is not designed to be used in numeric context: it relies on a variable to call the appropriate methods to get its numeric value (Of course, an array object could define FETCHNUM to
delegate to FETCHSIZE: but that obscures the point: a variable's type defines which methods are called in various contexts).

Now consider a more extreme (and probably very bad) example: imagine
we want to (lexically) redefine how an array behaves in numeric context: Lets say that we want it to use the sum of its elements, not its size. We don't want to modify the object itself (except to give it the C<sum> method): we simply want Perl to use the object slightly differently:

my @a = (1,2,3) but implements_sum_method; # add .sum method to vtable
my SummingArray $b := @a;

The type of $b refers to the variable's type, not the object's. Let us suppose that the type-definition syntax allows us to tell perl: "when you use this variable in numeric context, call your object's C<sum> method.". now, when we code

print @a + $b;

perl maps this to

print @a.FETCHSIZE + $b.sum;

and prints 9.

We don't need the variable-type magic, of course. We could have just said

print @a + @a.sum;

and gotten the same result. But the ability to express the behaviour of variables, independently of values, could be useful (and more powerful than a c<tie>).


Dave.

Reply via email to