class Junction
Logical superposition of values
is Mu
A junction is an unordered composite value of zero or more values. Junctions autothread over many operations, which means that the operation is carried out for each junction element (also known as 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 so
or ?
prefix operators. The semantics of this collapse depend on the junction type, which can be all
, any
, one
or none
.
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 |
As the table shows, in order to create junctions, you use the string that represents the type followed by any object, or else call .all
, .none
or .one
on the object.
say so 3 == (1..30).one; # OUTPUT: «True»say so ("a" ^ "b" ^ "c") eq "a"; # OUTPUT: «True»
Junctions are very special objects. They fall outside the Any
hierarchy, being only, as any other object, subclasses of Mu. That enables a feature for most methods: autothreading. Autothreading happens when a junction is bound to a parameter of a code object that doesn't accept values of type Junction
. Instead of producing an error, the signature binding is repeated for each value of the junction.
Example:
my = 1|2;if 3 == + 1
First autothreads over the infix:<+>
operator, producing the Junction 2|3
. The next autothreading step is over infix:<==>
, which produces False|True
. The if
conditional evaluates the junction in boolean context, which collapses it to True
. So the code prints yes\n
.
The type of a Junction
does not affect the number of items in the resultant Junction
after autothreading. For example, using a one Junction
during Hash key lookup, still results in a Junction
with several items. It is only in boolean context would the type of the Junction
come into play:
my = :42foo, :70bar;say :exists; # OUTPUT: «one(True, False)»say so :exists; # OUTPUT: «True»say :exists; # OUTPUT: «one(True, True)»say so :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.
Autothreading implies that the function that's autothreaded will also return a Junction of the values that it would usually return.
(1..3).head( 2|3 ).say; # OUTPUT: «any((1 2), (1 2 3))»
Since .head
returns a list, the autothreaded version returns a Junction
of lists.
(1..3).contains( 2&3 ).say; # OUTPUT: «all(True, True)»
Likewise, .contains
returns a Boolean; thus, the autothreaded version returns a Junction
of Booleans. In general, all methods and routines that take an argument of type T
and return type TT
, will also accept junctions of T
, returning junctions of TT
.
Implementations are allowed to short-circuit Junctions. For example one or more routine calls (a()
, b()
, or 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):
if a() | b() | c()
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 Set or a related type instead.
Usage examples:
my = <1 2 "Great">;.append(True).append(False);my = grep Bool|Int, ;sub is_prime(Int ) returns Boolmy = grep & / 1$ /, 2..100;say ; # OUTPUT: «[11 31 41 61 71]»my = <~ .git>;for dir(".")
Special care should be taken when using all
with arguments that may produce an empty list:
my = ();say so all() # True, because there are 0 False's
To express "all, but at least one", you can use @a && all(@a)
my = ();say so && all(); # OUTPUT: «False»
Negated operators are special-cased when it comes to autothreading. $a !op $b
is rewritten internally as !($a op $b)
. The outer negation collapses any junctions, so the return value always a plain Bool.
my = 'yes';my = <no none never>;if !eq any
Note that without this special-casing, an expression like $word ne any @words
would always evaluate to True
for non-trivial lists on one side.
For this purpose, infix:<ne>
counts as a negation of infix:<eq>
.
In general it is more readable to use a positive comparison operator and a negated junction:
my = 'yes';my = <no none never>;if eq none
Failures and exceptions
Failures are just values like any other, as far as Junctions are concerned:
my = +any "not a number", "42", "2.1";my = gather for ->.say; # OUTPUT: «[42 2.1]»
Above, we've used prefix +
operator on a Junction to coerce the strings inside of it to Numeric. Since the operator returns a Failure when a Str that doesn't contain a number gets coerced to Numeric
, one of the elements in the Junction
is a Failure
. Failures do not turn into exceptions until they are used or sunk, but we can check for definedness to avoid that. That is what we do in the loop that runs over the elements of the junction, adding them to a list only if they are defined.
The exception will be thrown, if you try to use the Failure
as a value—just like as if this Failure
were on its own and not part of the Junction
:
my = +any "not a number", "42", "2.1";try say == 42;$! and say "Got exception: $!.^name()";# OUTPUT: «Got exception: X::Str::Numeric»
Note that if an exception gets thrown when any of the values in a Junction get computed, it will be thrown just as if the problematic value were computed on its own and not with a Junction
; you can't just compute the values that work while ignoring exceptions:
sub calc ()my = any 1..42;say try calc ; # OUTPUT: «Nil»
Only one value above causes an exception, but the result of the try
block is still a Nil. A possible way around it is to cheat and evaluate the values of the Junction
individually and then re-create the Junction
from the result:
sub calc ()my = any 1..42;= any (gather ».take).grep: ;say so == 42; # OUTPUT: «True»
Smartmatching
Note that using Junction
s on the right-hand side of ~~
works slightly differently than using Junctions with other operators.
Consider this example:
say 25 == (25 | 42); # OUTPUT: «any(True, False)» – Junctionsay 25 ~~ (25 | 42); # OUTPUT: «True» – Bool
The reason is that ==
(and most other operators) are subject to auto-threading, and therefore you will get a Junction as a result. On the other hand, ~~
will call .ACCEPTS
on the right-hand-side (in this case on a Junction) and the result will be a Bool
.
Methods
method new
Defined as:
multi method new(Junction: \values, Str :!)multi method new(Junction: Str \type, \values)
Constructor to define a new Junction from the type that defines de Junction and a set of values.
my = Junction.new(<Þor Oðinn Loki>, type => "all");my = Junction.new( "one", 1..6 )
method defined
Defined as:
multi method defined(Junction:)
Checks for definedness instead of Boolean values.
say ( 3 | Str).defined ; # OUTPUT: «True»say (one 3, Str).defined; # OUTPUT: «True»say (none 3, Str).defined; # OUTPUT: «False»
Failure
s are also considered non-defined:
my =Failure.new;say (one 3, ).defined; # OUTPUT: «True»
Since 6.d, this method will autothread.
method Bool
Defined as:
multi method Bool(Junction:)
Collapses the Junction
and returns a single Boolean value according to the type and the values it holds. Every element is transformed to Bool
.
my = Junction.new( "one", 1..6 );say .Bool; # OUTPUT: «False»
All elements in this case are converted to True
, so it's false to assert that only one of them is.
my = Junction.new( "one", <0 1> );say .Bool; # OUTPUT: «True»
Just one of them is truish in this case, 1
, so the coercion to Bool
returns True
.
method Str
Defined as:
multi method Str(Junction:)
Autothreads the .Str
method over its elements and returns results as a Junction. Output methods that use .Str
method (print and put) are special-cased to autothread junctions, despite being able to accept a Mu type.
method gist
Defined as:
multi method gist(Junction:)
Collapses the Junction and returns a Str composed of the type of the junction and the gists of its components:
<a 42 c>.all.say; # OUTPUT: «all(a, 42, c)»
method perl
Defined as:
multi method perl(Junction:)
Collapses the Junction and returns a Str composed of perls of its components that evaluates to the equivalent Junction with equivalent components:
<a 42 c>.all.perl.put; # OUTPUT: «all("a", IntStr.new(42, "42"), "c")»
infix ~
Defined as:
multi sub infix:<~>(Str , Junction )multi sub infix:<~>(Junction , Str )multi sub infix:<~>(Junction \a, Junction \b)
The infix ~
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:
my = 1|3|5;my = 2|4|6;my = ~ ;say ; #OUTPUT: «any(12, 14, 16, 32, 34, 36, 52, 54, 56)»say "Found 34!" if 34 == ; #OUTPUT: «Found 34!»my = "0" ~ ;say "Found 03" if "03" == ; #OUTPUT: «Found 03!»my = ~ "1";say "Found 11" if 11 == ; #OUTPUT: «Found 11!»
On the other hand, the versions of ~
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.
See Also
http://perl6maven.com/perl6-is-a-value-in-a-given-list-of-values
https://perl6advent.wordpress.com/2009/12/13/day-13-junctions/