/
Junction.pod6
287 lines (202 loc) · 10.1 KB
/
Junction.pod6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
=begin pod
=TITLE class Junction
=SUBTITLE Logical superposition of values
class Junction is Mu { }
A junction is an unordered composite value of zero or more values. Junctions
I<autothread> over many operations, which means that the operation
is carried out for each junction element (also known as I<eigenstate>), and
the result is junction of the return values of all those operators.
Junctions collapse into a single value in boolean context, so when used in a
conditional, a negation or an explicit coercion to Bool through the C<so> or
C<?> prefix operators. The semantics of this collapse
depend on the I<junction type>, which can be C<all>, C<any>, C<one> or
C<none>.
=begin table
type | constructor | operator | True if ...
=====+================+============+===========
all | all | & | no value evaluates to False
any | any | \| | at least one value evaluates to True
one | one | ^ | exactly one value evaluates to True
none | none | | no value evaluates to True
=end table
As the table shows, in order to create junctions, you use the string that
represents the type followed by any object, or else call
L<C<.all>|/routine/all>, L<C<.none>|/routine/none> or L<C<.one>|/routine/one> on
the object.
say so 3 == (1..30).one; # OUTPUT: «True»
say so ("a" ^ "b" ^ "c") eq "a"; # OUTPUT: «True»
Autothreading happens when a junction is bound to a parameter of a code object
that doesn't accept values of type C<Junction>. Instead of producing an error,
the signature binding is repeated for each value of the junction.
Example:
my $j = 1|2;
if 3 == $j + 1 {
say 'yes';
}
First autothreads over the C<< infix:<+> >> operator, producing the Junction
C<2|3>. The next autothreading step is over C<< infix:<==> >>, which produces
C<False|True>. The C<if> conditional evaluates the junction in boolean
context, which collapses it to C<True>. So the code prints C<yes\n>.
The type of a C<Junction> does I<not> affect the number of items in the
resultant C<Junction> after autothreading. For example, using a
L<one|/routine/one> C<Junction> during L<Hash|/type/Hash> key lookup, still
results in a C<Junction> with several items. It is only in boolean context would
the type of the C<Junction> come into play:
my %h = :42foo, :70bar;
say %h{one <foo meow>}:exists; # OUTPUT: «one(True, False)»
say so %h{one <foo meow>}:exists; # OUTPUT: «True»
say %h{one <foo bar>}:exists; # OUTPUT: «one(True, True)»
say so %h{one <foo bar>}:exists; # OUTPUT: «False»
Note that the compiler is allowed, but not required, to parallelize
autothreading (and Junction behavior in general), so it is usually an
error to autothread junctions over code with side effects.
Implementations are allowed to short-circuit Junctions. For example one or more
routine calls (C<a()>, C<b()>, or C<c()>) in the code below might not get
executed at all, if the result of the conditional has been fully determined
from routine calls already performed (only one truthy return value is enough
to know the entire Junction is true):
=begin code :preamble<sub a(){}; sub b(){}; sub c(){}>
if a() | b() | c() {
say "At least one of the routines was called and returned a truthy value"
}
=end code
Junctions are meant to be used as matchers in boolean context; introspection
of junctions is not supported. If you feel the urge to introspect a junction,
use a L<Set|/type/Set> or a related type instead.
Usage examples:
my @list = <1 2 "Great">;
@list.append(True).append(False);
my @bool_or_int = grep Bool|Int, @list;
sub is_prime(Int $x) returns Bool {
# 'so' is for boolean context
so $x %% none(2..$x.sqrt);
}
my @primes_ending_in_1 = grep &is_prime & / 1$ /, 2..100;
say @primes_ending_in_1; # OUTPUT: «[11 31 41 61 71]»
my @exclude = <~ .git>;
for dir(".") { say .Str if .Str.ends-with(none @exclude) }
Special care should be taken when using C<all> with arguments that may
produce an empty list:
my @a = ();
say so all(@a) # True, because there are 0 False's
To express "all, but at least one", you can use C<@a && all(@a)>
my @a = ();
say so @a && all(@a); # OUTPUT: «False»
Negated operators are special-cased when it comes to autothreading.
C<$a !op $b> is rewritten internally as C<!($a op $b)>. The outer
negation collapses any junctions, so the return value always a plain
L<Bool|/type/Bool>.
my $word = 'yes';
my @negations = <no none never>;
if $word !eq any @negations {
say '"yes" is not a negation';
}
Note that without this special-casing, an expression like
C<$word ne any @words> would always evaluate to C<True> for non-trivial lists
on one side.
For this purpose, C<< infix:<ne> >> counts as a negation of C<< infix:<eq> >>.
In general it is more readable to use a positive comparison operator and
a negated junction:
my $word = 'yes';
my @negations = <no none never>;
if $word eq none @negations {
say '"yes" is not a negation';
}
=head1 Failures and Exceptions
L<Failures|/type/Failure> are just values like any other, as far as Junctions
are concerned:
my $j = +any "not a number", "42", "2.1";
(gather $j».take).grep(Numeric).say; # OUTPUT: «(42 2.1)»
Above, we've used prefix C<+> operator on a L<Junction|/type/Junction> to coerce
the strings inside of it to L<Numeric|/type/Numeric>. Since the operator returns
a L<Failure|/type/Failure> when L<Str|/type/Str> that doesn't contain a number
gets coerced to C<Numeric>, one of the elements in the C<Junction> is a
C<Failure>, but same C<Failure> rules as normal apply and the C<Failure> doesn't
explode just because it's in a C<Junction>, and we can L«C<.grep>|/routine/grep»
it out. The exception I<will> be thrown, if you try to use the C<Failure> as a
value—just like were this C<Failure> on its own and not part of the C<Junction>:
my $j = +any "not a number", "42", "2.1";
try say $j == 42;
$! and say "Got exception: $!.^name()"; # OUTPUT: «Got exception: X::Str::Numeric»
Note that if an exception gets thrown when I<any> of the values in a
L<Junction|/type/Junction> get computed, it will be thrown just as if the
problematic value were computed on its own and not with a C<Junction>; you can't
just compute the values that work while ignoring exceptions:
sub calc ($_) { die when 13 }
my $j = any 1..42;
say try calc $j; # OUTPUT: «Nil»
Only one value above causes an exception, but the result of the L«C<try>
block|/language/exceptions#index-entry-try_blocks-try» is still a
L<Nil|/type/Nil>. A possible way around it is to cheat and evaluate the values
of the C<Junction> individually and then re-create the C<Junction> from the
result:
sub calc ($_) { die when 13 }
my $j = any 1..42;
$j = any (gather $j».take).grep: {Nil !=== try calc $_};
say so $j == 42; # OUTPUT: «True»
=head1 Smartmatching
Note that using Junctions on the right-hand side of C<~~> works
slightly differently than using Junctions with other operators.
Consider this example:
say 25 == (25 | 42); # OUTPUT: «any(True, False)» – Junction
say 25 ~~ (25 | 42); # OUTPUT: «True» – Bool
The reason is that C<==> (and most other operators) are subject to
auto-threading, and therefore you will get a Junction as a result. On
the other hand, C<~~> will call C<.ACCEPTS> on the right-hand-side (in
this case on a Junction) and the result will be a C<Bool>.
=head1 Methods
=head2 method new
Defined as:
multi method new(Junction: \values, Str :$type!)
multi method new(Junction: Str:D \type, \values)
Constructor to define a new Junction from the type that defines de Junction and
a set of values.
my $j = Junction.new(<Þor Oðinn Loki>, type => "all");
my $n = Junction.new( "one", 1..6 )
=head2 method Str
Defined as:
multi method Str(Junction:D:)
Autothreads the C<.Str> method over its elements and returns results as a
L<Junction|/type/Junction>. Output methods that use C<.Str> method
(L<print|/routine/print> and L<put|/routine/put>) are special-cased to
autothread junctions, despite being able to accept a L<Mu|/type/Mu> type.
=head2 method gist
Defined as:
multi method gist(Junction:D:)
Collapses the L<Junction|/type/Junction> and returns a L<Str|/type/Str> composed of the type of the junction and the
L<gists|/routine/gist> of its components:
<a 42 c>.all.say; # OUTPUT: «all(a, 42, c)»
=head2 method perl
Defined as:
multi method perl(Junction:D:)
Collapses the L<Junction|/type/Junction> and returns a L<Str|/type/Str> composed of L<perls|/routine/perl> of its components
that L<evaluates|/routine/EVAL> to the equivalent L<Junction|/type/Junction> with equivalent components:
<a 42 c>.all.perl.put; # OUTPUT: «all("a", IntStr.new(42, "42"), "c")»
=head2 infix C<~>
Defined as:
multi sub infix:<~>(Str:D $a, Junction:D $b)
multi sub infix:<~>(Junction:D $a, Str:D $b)
multi sub infix:<~>(Junction:D \a, Junction:D \b)
The infix C<~> concatenation can be used to merge junctions into a single one or
merge Junctions with strings. The resulting junction will have all elements
merged as if they were joined into a nested loop:
=begin code
my $odd = 1|3|5;
my $even = 2|4|6;
my $merged = $odd ~ $even;
say $merged; #OUTPUT: «any(12, 14, 16, 32, 34, 36, 52, 54, 56)»
say "Found 34!" if 34 == $merged; #OUTPUT: «Found 34!»
my $prefixed = "0" ~ $odd;
say "Found 03" if "03" == $prefixed; #OUTPUT: «Found 03!»
my $postfixed = $odd ~ "1";
say "Found 11" if 11 == $postfixed; #OUTPUT: «Found 11!»
=end code
On the other hand, the versions of C<~> that use a string as one argument will
just concatenate the string to every member of the Junction, creating another
Junction with the same number of elements.
=head1 See Also
=item L<https://perlgeek.de/blog-en/perl-5-to-6/08-junctions.html>
=item L<http://perl6maven.com/perl6-is-a-value-in-a-given-list-of-values>
=item L<https://perl6advent.wordpress.com/2009/12/13/day-13-junctions/>
=end pod
# vim: expandtab softtabstop=4 shiftwidth=4 ft=perl6