YAP6 Operator: Coercion Operators

by Adriano Ferreira

Another article of the series "Yet Another Perl 6 Operator"

In Perl 5, we expect values to DWIM ("do what I mean") in various contexts. For example, if we use a string containg "42" as a number we expect it automagically act as a number. Perl 6 keeps this tradition of DWIMmery and introduces several new explicit coercion operations.

? to get booleans
+ to get numbers
~ to get strings


2007-09-26 12:40:06
How does print ~($x + 1); know to evaluate to 'XLIII' ? Why doesn't it evaluate to '43' or throw an error? What makes it take on the Roman type, because it was first in the expression?
A different Joe
2007-09-26 19:36:31
How many digits are in the stringification of a non-integral number? For example, what is the value of ~(1.0 / 3) ?
Adriano Ferreira
2007-09-26 19:49:13

The statement

print $x + 1; # 43

was corrected to
print +($x + 1); # 43

The issue here is that modelling roman numbers, besides overloading ~ and + (string and numeric coercion), the addition must be overloaded as well, resulting in a new Roman number. So $x+$x, $x+1, $x+'I' could preserve their nature. So $x+1 should result an equivalent Roman.new(43) in this case.

A Perl 5 implementation of this is Acme::Roman.

Adriano Ferreira
2007-09-26 19:54:15
@A different Joe

The answer will be quite similar to what we got today with Perl 5:

$ perl -e '$a = 1.0/3; print "$a"'

where the result comes from some equivalent of applying a format like "sprintf '%.15f'".

2007-09-28 16:32:44
Does the auto-decrement operator have magic now? That was soo annoying to have such a cool feature on the one side and not the other...

The specific magic I'm speaking of is...

my $foo = 'D';
$foo++; # 'E'
$foo--; # -1 .... ARGggh!!

Adriano Ferreira
2007-09-28 17:28:41

Does the auto-decrement operator have magic now?

In fact, it does. You should be able to do something like:

my $foo = 'picAA99.gif'
$foo++; # 'picAB00.gif'
$foo--; # 'picAA99.dif'

And the details of how Perl 6 handles that is the subject of one of the articles of the next week.