On Monday, November 25, 2002, at 12:27 PM, Tanton Gibbs wrote:
Perl 5 did not have typecasts...probably for good reason. The quip in the camel book says that no one likes to be typecast, anyway. I would rather not have typecasts in Perl6 if we can get by without them.Well... Perl5 didn't have typecasts primarily because it didn't have types. To the extent it _does_ have types, it has casting, too: it just is extremely limited.
my $s = scalar <blah>;
my $s = list <blah>;
The above can be construed as typecasting: converting an expression <blah> to either a scalar or list "type", but only if it isn't that type already.
So by Perl6 "casting", I mean the transformation of one type to another, whether automatic:
my num $i = 5.0;
my str $s = $i; # cast $i to 'str'
or explicit:
my $i = str 5.0; # cast the literal number 5.0 to a str
Casting and context are closely related, and both are required (I would hope) for multimethods. If you have a multimethod:
sub foo (int $var);
sub foo (str $var);
and you call it like this:
&foo($myval);
.... the multimethod dispatcher needs to know if $myval is closer to an int, or a str, or something that can be easily/trivially cast to an int or str. If I make a subclass of C<str> called C<MyString>, the &foo dispatcher should know that a MyString is a str, and call the str-based multimethod variant:
my MyString $mystring = MyString.new('hello');
&foo($mystring); # knows to call foo(str), not foo(int)
My hope is that there is little difference between builtin and user-defined types/classes, such that both use the same syntax and have the same features wrt context and casting:
my str $s = $var; # evaluate $var in str context
my MyClass $s = $var; # evaluate $var in MyClass context
my $s = str $var; # cast $var to str
my $s = MyClass $var; # cast $var to MyClass
my MyClass $myclass = MyClass.new;
my str $as_string = $myclass; # cast $myclass to string
my int $as_int = $myclass; # cast $myclass to integer
.... this implies that the want() function can identify context as narrowly or as broadly as is needed:
# class str is scalar;
# class MyString is str;
my MyString $s = &foo('bar'); # in C<MyString> context
such that within &foo:
want scalar; # TRUE
want str; # TRUE
want MyString; # TRUE
want hash; # FALSE
MikeL