Skip to content

Commit 08e976b

Browse files
committed
Adds numeric context
Refs #1225 and #124
1 parent 544bd80 commit 08e976b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

doc/Language/contexts.pod6

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,34 @@ You can force that sink context on L<Iterator>s, by using the L<C<sink-all>|/rou
1919
2020
In general, blocks will warn if evaluated in sink context; however, L<gather/take blocks|/language/control#Flow%29_gather_take> are explicitly evaluated in sink context, with values returned explicitly using C<take>.
2121
22+
=head1 Number
23+
24+
This context, and probably all of them except sink above, are I<conversion> or I<interpretation> contexts in the sense that they take an untyped or typed variable and duck-type it to whatever is needed to perform the operation. In some cases that will imply a conversion (from L<Str> to L<Int>, for instance); in other cases simply an interpretation (L<IntStr> will be interpreted as L<Int> or as L<Str>).
25+
26+
I<Number context> is called whenever we need to apply a numerical operation on a variable.
27+
28+
=begin code
29+
my $not-a-string="1 ";
30+
my $neither-a-string="3 ";
31+
say $not-a-string+$neither-a-string; # OUTPUT: «4␤»
32+
=end code
33+
34+
In the code above, strings will be interpreted in numeric context as long as there is only some numbers and no other characters. It can have any number of leading or trailing whitespace, however.
35+
36+
Numeric context can be forced by using arithmetic operators such as C<+> or C<->. In that context, the L<C<Numeric>|/routine/Numeric> method will be called if available and the value returned used as the numeric value of the object.
37+
38+
=begin code
39+
my $t = True;
40+
my $f = False;
41+
say $t+$f; # OUTPUT: «1␤»
42+
say $t.Numeric; # OUTPUT: «1␤»
43+
say $f.Numeric; # OUTPUT: «0␤»
44+
my $list= <a b c>;
45+
say True+$list; # OUTPUT: «4␤»
46+
=end code
47+
48+
In the case of I<listy> things, the numeric value will be in general equivalent to C<.elems>; in some cases, like L<Thread|/Numeric#(Thread)_method_Numeric> it will return an unique thread identifier.
49+
2250
=end pod
2351

2452
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6

0 commit comments

Comments
 (0)