class Junction

Logical superposition of values

class Junction 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. The semantics 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

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 $j = 1|2;
if 3 == $j + 1 {
    say 'yes';
}

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.

Note that the compiler is allowed to parallelize and short-circuit autothreading (and Junction behavior in general), so it is usually an error to autothread junctions over code with side effects.

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 @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;        # 11 31 41 61 71

Special care should be taken when using all with arguments that may produce an empty list:

my @a = ();
so all(@a) # True, because there are 0 False's

To express "all, but at least one", you can use @a && all(@a) say so @a && all(@a); # 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>. 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 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';
}

See Also

Type graph

Below you should see a clickable image showing the type relations for Junction that links to the documentation pages for the related types. If not, try the PNG version instead.

perl6-type-graph Junction Junction Mu Mu Junction->Mu

Routines supplied by class Mu

Junction inherits from class Mu, which provides the following methods:

routine defined

multi sub    defined(Mu) returns Bool:D
multi method defined()   returns Bool:D

Returns False on the type object, and True otherwise.

say Int.defined;                # False
say 42.defined;                 # True

Very few types (like Failure) override defined to return False even for instances:

sub fails() { fail 'oh noe' };
say fails().defined;            # False

routine Bool

multi sub    Bool(Mu) returns Bool:D
multi method Bool()   returns Bool:D

Returns False on the type object, and True otherwise.

Many built-in types override this to be False for empty collections, the empty string or numerical zeros

say Mu.Bool;                    # False
say Mu.new.Bool;                # True
say [1, 2, 3].Bool;             # True
say [].Bool;                    # False
say { 'hash' => 'full'}.Bool;   # True
say {}.Bool;                    # False

method Str

multi method Str()   returns Str

Returns a string representation of the invocant, intended to be machine readable. Method Str warns on type objects, and produces the empty string.

say Mu.Str;                     #!> use of uninitialized value of type Mu in string context

routine gist

multi sub    gist(Mu) returns Str
multi method gist()   returns Str

Returns a string representation of the invocant, optimized for fast recognition by humans.

The default gist method in Mu re-dispatches to the perl method for defined invocants, and returns the type name in parenthesis for type object invocants. Many built-in classes override the case of instances to something more specific.

gist is the method that say calls implicitly, so say $something and say $something.gist generally produce the same output.

say Mu.gist;        # (Mu)
say Mu.new.gist;    # Mu.new()

routine perl

multi sub    perl(Mu) returns Str
multi method perl()   returns Str

Returns a Perlish representation of the object (i.e., can usually be re-evaluated with EVAL to regenerate the object). The exact output of perl is implementation specific, since there are generally many ways to write a Perl expression that produces a particular value

method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. If named arguments are passed to it, their values are used in every place where an attribute name matches the name of a named argument.

class Point2D {
    has ($.x, $.y);
    multi method gist(Point2D:D:) {
        "Point($.x, $.y)";
    }
}

my $p = Point2D.new(x => 2, y => 3);

say $p;                     # Point(2, 3)
say $p.clone(y => -5);      # Point(2, -5)

method new

multi method new(*%attrinit)

Default method for constructing (create + initialize) new objects of a class. This method expects only named arguments which are then used to initialize attributes with accessors of the same name.

Classes may provide their own new method to override this default.

new triggers an object construction mechanism that calls submethods named BUILD in each class of an inheritance hierarchy, if they exist. See the documentation on object construction for more information.

method bless

method bless(*%attrinit) returns Mu:D

Lower-level object construction method than new.

Creates a new object of the same type as the invocant, uses the named arguments to initialize attributes, and returns the created object.

You can use this method when writing custom constructors:

class Point {
    has $.x;
    has $.y;
    multi method new($x, $y) {
        self.bless(:$x, :$y);
    }
}
my $p = Point.new(-1, 1);

(Though each time you write a custom constructor, remember that it makes subclassing harder).

method CREATE

method CREATE() returns Mu:D

Allocates a new object of the same type as the invocant, without initializing any attributes.

say Mu.CREATE.defined;  # True

method print

multi method print() returns Bool:D

Prints value to $*OUT after stringification using .Str method without adding a newline at end.

"abc\n".print;          # abc

method say

multi method say() returns Bool:D

Prints value to $*OUT after stringification using .gist method with newline at end.

say 42;                 # 42

method ACCEPTS

multi method ACCEPTS(Mu:U: $other)

ACCEPTS is the method that smart matching with the infix ~~ operator and given/when invokes on the right-hand side (the matcher).

The Mu:U multi performs a type check. Returns True if $other conforms to the invocant (which is always a type object or failure).

say 42 ~~ Mu;           # True
say 42 ~~ Int;          # True
say 42 ~~ Str;          # False

Note that there is no multi for defined invocants; this is to allow autothreading of junctions, which happens as a fallback mechanism when no direct candidate is available to dispatch to.

method WHICH

multi method WHICH() returns ObjAt:D

Returns an object of type ObjAt which uniquely identifies the object. Value types override this method which makes sure that two equivalent objects return the same return value from WHICH.

say 42.WHICH eq 42.WHICH;       # True

method WHERE

method WHERE() returns Int

Returns an Int representing the memory address of the object.

method WHY

multi method WHY()

Returns the attached Pod value. For instance,

    sub cast(Spell $s)
    #= Initiate a specified spell normally
    #= (do not use for class 7 spells)
    {
	do-raw-magic($s);
    }
    say &cast.WHY;

prints

Initiate a specified spell normally (do not use for class 7 spells)

See the documentation specification for details about attaching Pod to variables, classes, functions, methods, etc.

trait is export

multi sub trait_mod:<is>(Mu:U \type, :$export!)

Marks a type as being exported, that is, available to external users.

my class SomeClass is export { }

A user of a module or class automatically gets all the symbols imported that are marked as is export.

method take

method take()

Takes the given item and passes it to the enclosing gather block.

#| randomly select numbers for lotto
my $num-selected-numbers = 6;
my $max-lotto-numbers = 49;
gather for ^$num-selected-numbers {
    take (1 .. $max-lotto-numbers).pick(1);
}.say;    #-> 32 22 1 17 32 9  (for example)

method so

method so()

Returns a Bool value representing the logical non-negation of an expression. One can use this method similarly to the English sentence: "If that is so, then do this thing". For instance,

my @args = <-a -e -b -v>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} #-> Verbose option detected in arguments

method not

method not()

Returns a Bool value representing the logical negation of an expression. Thus it is the opposite of so.

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments

Since there is also a prefix version of not, the above code reads better like so:

my @args = <-a -e -b>;
my $verbose-selected = any(@args) eq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} #-> Verbose option not present in arguments