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 the 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 command that represents the type of Junction 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 $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.

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 %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.

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.

'walking on sunshine'.contains( 'king'&'sun' ).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() {
    say "At least one of the routines was called and returned a truthy value"
}

Junctions are meant to be used as matchers in a 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 @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 all with arguments that may produce an empty list:

my @a = ();
    say so all(@a) # True, because there are 0 Falses

To express "all, but at least one", you can use @a && all(@a)

my @a = ();
    say so @a && all(@a);   # 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 $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 $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 $word = 'yes';
    my @negations = <no none never>;
    if $word eq none @negations {
        say '"yes" is not a negation';
    }

Failures and exceptions

Failures are just values like any other, as far as Junctions are concerned:

my $j = +any "not a number", "42", "2.1";
    my @list = gather for $j -> $e {
        take $e if $e.defined;
    }
    @list.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 $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 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 ($_) { 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 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 ($_) { die when 13 }
    my $j = any 1..42;
    $j = any (gather $jĀ».take).grep: {Nil !=== try calc $_};
    say so $j == 42; # OUTPUT: Ā«Trueā¤Ā»

Smartmatching

Note that using Junctions 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)ā¤Ā» ā€“ Junction
    say 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

multi method new(Junction: \values, Str :$type!)
    multi method new(Junction: Str:D \type, \values)

These constructors build a new junction from the type that defines it and a set of values.

my $j = Junction.new(<ƞor Oưinn Loki>, type => "all");
    my $n = Junction.new( "one", 1..6 )

The main difference between the two multis is how the type of the Junction is passed as an argument; either positionally as the first argument, or as a named argument using type.

method defined

multi method defined(Junction:D:)

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ā¤Ā»

Failures are also considered non-defined:

my $foo=Failure.new;
    say (one 3, $foo).defined; # OUTPUT: Ā«Trueā¤Ā»

Since 6.d, this method will autothread.

method Bool

multi method Bool(Junction:D:)

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 $n = Junction.new( "one", 1..6 );
say $n.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 $n = Junction.new( "one", <0 1> );
say $n.Bool;                         # OUTPUT: Ā«Trueā¤Ā»

Just one of them is truish in this case, 1, so the coercion to Bool returns True.

method Str

multi method Str(Junction:D:)

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 iterator

multi method iterator(Junction:D:)

Returns an iterator over the Junction converted to a List.

method gist

multi method gist(Junction:D:)

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 raku

multi method raku(Junction:D:)

Collapses the Junction and returns a Str composed of raku of its components that evaluates to the equivalent Junction with equivalent components:

<a 42 c>.all.raku.put; # OUTPUT: Ā«all("a", IntStr.new(42, "42"), "c")ā¤Ā»

infix ~

multi infix:<~>(Str:D $a, Junction:D $b)
    multi infix:<~>(Junction:D $a, Str:D $b)
    multi infix:<~>(Junction:D \a, Junction:D \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 $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!ā¤Ā»

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

See Also

class int

Native integer

class Allomorph

Dual value number and string

class Any

Thing/object

class AST

Abstract representation of a piece of source code

class atomicint

Integer (native storage at the platform's atomic operation size)

class Block

Code object with its own lexical scope

class CallFrame

Captures the current frame state

class Code

Code object

class Collation

Encapsulates instructions about how strings should be sorted

class Compiler

Information related to the compiler that is being used

class Complex

Complex number

class ComplexStr

Dual value complex number and string

class Cool

Object that can be treated as both a string and number

class CurrentThreadScheduler

Scheduler that synchronously executes code on the current thread

class Date

Calendar date

class DateTime

Calendar date with time

class Distribution::Hash

Distribution::Hash

class Distribution::Locally

Distribution::Locally

class Distribution::Path

Distribution::Path

class Distribution::Resource

Every one of the resources installed with a distribution

class Duration

Length of time

class Encoding::Registry

Management of available encodings

class FatRat

Rational number (arbitrary-precision)

class ForeignCode

Rakudo-specific class that wraps around code in other languages (generally NQP)

class Format

Convert values to a string given a format specification

class Formatter

Produce Callable for given format specification

class HyperSeq

An object for performing batches of work in parallel with ordered output

class HyperWhatever

Placeholder for multiple unspecified values/arguments

class Instant

Specific moment in time

class Int

Integer (arbitrary-precision)

class IntStr

Dual value integer and string

class Label

Tagged location in the source code

class Lock::Async

A non-blocking, non-re-entrant, mutual exclusion lock

class Macro

Compile-time routine

class Method

Member function

class Mu

The root of the Raku type hierarchy.

class Nil

Absence of a value or a benign failure

class Num

Floating-point number

role Numeric

Number or object that can act as a number

class NumStr

Dual value floating-point number and string

class ObjAt

Unique identification for an object

class Parameter

Element of a Signature

class Perl

Perl related information

class Proxy

Item container with custom storage and retrieval

class RaceSeq

Performs batches of work in parallel without respecting original order.

class Raku

Raku related information

package RakuAST

Namespace for holding RakuAST related classes

class RakuAST::Doc::Block

Contains the information of a RakuDoc block

class RakuAST::Doc::Declarator

Contains the declarator docs of a RakuAST object

class RakuAST::Doc::Markup

Contains the information about RakuDoc markup

class RakuAST::Doc::Paragraph

Contains the information about a RakuDoc paragraph

class Rat

Rational number (limited-precision)

class RatStr

Dual value rational number and string

class Routine

Code object with its own lexical scope and return handling

class Routine::WrapHandle

Holds all information needed to unwrap a wrapped routine.

class Scalar

A mostly transparent container used for indirections

class Signature

Parameter list pattern

class Str

String of characters

class StrDistance

Contains the result of a string transformation.

class Sub

Subroutine

class Submethod

Member function that is not inherited by subclasses

class Telemetry

Collect performance state for analysis

class Telemetry::Instrument::Thread

Instrument for collecting Thread data

class Telemetry::Instrument::ThreadPool

Instrument for collecting ThreadPoolScheduler data

class Telemetry::Instrument::Usage

Instrument for collecting getrusage data

class Telemetry::Period

Performance data over a period

class Telemetry::Sampler

Telemetry instrument pod

Subset UInt

Unsigned integer (arbitrary-precision)

class ValueObjAt

Unique identification for value types

class Variable

Object representation of a variable for use in traits

class Version

Module version descriptor

class Whatever

Placeholder for the value of an unspecified argument

class WhateverCode

Code object constructed by Whatever-priming

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.