class Supply

Asynchronous data stream with multiple subscribers

class Supply {}

A supply is a thread-safe, asynchronous data stream like a Channel, but it can have multiple subscribers (taps) that all get the same values flowing through the supply.

It is a thread-safe implementation of the Observer Pattern, and central to supporting reactive programming in Perl 6.

There are two types of Supplies: live and on demand. When tapping into a live supply, the tap will only see values that are flowing through the supply after the tap has been created. Such supplies are normally infinite in nature, such as mouse movements. Closing such a tap does not stop mouse events from occurring, it just means that the values will go by unseen. All tappers see the same flow of values.

A tap on an on demand supply will initiate the production of values, and tapping the supply again may result in a new set of values. For example, Supply.interval produces a fresh timer with the appropriate interval each time it is tapped. If the tap is closed, the timer simply stops emitting values to that tap.

A live Supply is obtained from the Supplier factory method Supply. New values are emitted by calling emit on the Supplier object.

my $supplier = Supplier.new;
my $supply = $supplier.Supply;
$supply.tap(-> $v { say "$v" });
$supplier.emit(42); # Will cause the tap to output "42" 

The live method returns True on live supplies. Factory methods such as interval, from-list will return on demand supplies.

Further examples can be found in the concurrency page.

Methods that return Taps

method tap

method tap(Supply:D: &emit = -> $ { },
        :&done,
        :&quit,
        :&closing,
    --> Tap:D)

Creates a new tap (a kind of subscription if you will), in addition to all existing taps. The first positional argument is a piece of code that will be called when a new value becomes available through the emit call.

The &done callback is called when the done method on the supply is called, indicating the end of life of the channel. For a live supply the done routine will be called on the parent Supplier.

The &quit callback is called when the quit method on the supply is called, indicating an erroneous termination of the supply. For a live supply the quit routine will be called on the parent Supplier

Method tap returns an object of type Tap, on which you can call the close method to cancel the subscription.

my $s = Supply.from-list(0 .. 5);
my $t = $s.tap(-> $v { say $v }done => { say "no more ticks" });

Produces:

0
1
2
3
4
5
no more ticks

method act

method act(Supply:D: &act --> Tap:D)

Creates a tap on the given supply with the given code. Differently from tap, the given code is guaranteed to be only executed by one thread at a time.

Utility methods

method Channel

method Channel(Supply:D: --> Channel:D)

Returns a Channel object that will receive all future values from the supply, and will be closed when the Supply is done, and quit (shut down with error) when the supply is quit.

method Promise

method Promise(Supply:D: --> Promise:D)

Returns a Promise that will be kept when the Supply is done. If the Supply also emits any values, then the Promise will be kept with the final value. Otherwise, it will be kept with Nil. If the Supply ends with a quit instead of a done, then the Promise will be broken with that exception.

my $supplier = Supplier.new;
my $s = $supplier.Supply;
my $p = $s.Promise;
$p.then(-> $v { say "got $v.result()" });
$supplier.emit('cha');         # not output yet 
$supplier.done();              # got cha 

The Promise method is most useful when dealing with supplies that will tend to produce just one value, when only the final value is of interest, or when only completion (successful or not) is relevant.

method live

method live(Supply:D: --> Bool:D)

Returns True if the supply is "live", that is, values are emitted to taps as soon as they arrive. Always returns True in the default Supply (but for example on the supply returned from Supply.from-list it's False).

say Supplier.new.Supply.live;    # OUTPUT: «True␤» 

method schedule-on

method schedule-on(Supply:D: $scheduler)

Runs the emit, done and quit callbacks on the specified scheduler.

This is useful for GUI toolkits that require certain actions to be run from the GUI thread.

Methods that wait until the supply is done

method wait

method wait(Supply:D:)

Waits until the supply is done (in which case it returns True) or quit (in which case it will throw the exception that was passed to quit).

my $s = Supplier.new;
start {
  sleep 1;
  say "One second: running.";
  sleep 1;
  $s.emit(42);
  $s.done;
}
$s.Supply.wait;
say "Two seconds: done";

method list

method list(Supply:D: --> List:D)

Waits until the supply is done, then returns a list of all values emitted since the list call.

method grab

method grab(Supply:D: &process --> Supply:D)

Waits until the given supply is done. It will then call the given process closure passing all of the values seen, Then creates a supply to which all values returned from the process closure.

method reverse

method reverse(Supply:D: --> Supply:D)

Waits until the given supply is done, then creates a supply to which all values seen are emitted in reverse order.

method sort

method sort(Supply:D: &by? --> Supply:D)

Waits until the given supply is done, then creates a supply to which all values seen are emitted in sorted order. Optionally accepts a comparator Block.

Methods that return another Supply

method from-list

method from-list(Supply:U: *@values --> Supply:D)

Creates an on-demand supply from the values passed to this method.

my $s = Supply.from-list(123);
$s.tap(&say);           # OUTPUT: «1␤2␤3␤» 

method share

method share(Supply:D: --> Supply:D)

Creates a live supply from an on-demand supply, thus making it possible to share the values of the on-demand supply on multiple taps, instead of each tap seeing its own copy of all values from the on-demand supply.

# this says in turn: "first 1" "first 2" "second 2" "first 3" "second 3" 
my $s = Supply.interval(1).share;
$s.tap: { "first $_".say };
sleep 1.1;
$s.tap: { "second $_".say };
sleep 2

method flat

method flat(Supply:D: --> Supply:D)

Creates a supply on which all of the values seen in the given supply are flattened before being emitted again.

method do

method do(Supply:D: &do --> Supply:D)

Creates a supply to which all values seen in the given supply, are emitted again. The given code, executed for its side-effects only, is guaranteed to be only executed by one thread at a time.

method interval

method interval(Supply:U: $interval$delay = 0 --> Supply:D)

Creates a supply that emits a value every $interval seconds, starting $delay seconds from the call. The value is an integer, starting from 0, and is incremented by one for each value emitted. Note that if the supplied interval is less than one millisecond it will be changed to one millisecond and a warning will be emitted.

method grep

method grep(Supply:D: Mu $test --> Supply:D)

Creates a new supply that only emits those values from the original supply that smart-match against $test.

my $supplier = Supplier.new;
my $all      = $supplier.Supply;
my $ints     = $all.grep(Int);
$ints.tap(&say);
$supplier.emit($_for 1'a string'3.14159;   # prints only 1 

method map

method map(Supply:D: &mapper --> Supply:D)

Returns a new supply that maps each value of the given supply through &mapper and emits it to the new supply.

my $supplier = Supplier.new;
my $all      = $supplier.Supply;
my $double   = $all.map(-> $value { $value * 2 });
$double.tap(&say);
$supplier.emit(4);           # RESULT: «8» 

method batch

method batch(Supply:D: :$elems:$seconds --> Supply:D)

Creates a new supply that batches the values of the given supply by either the number of elements in the batch (using :elems) or the maximum number of seconds (using the :seconds) or both. Any remaining values are emitted in a final batch when the supply is done.

method elems

method elems(Supply:D: $seconds? --> Supply:D)

Creates a new supply in which changes to the number of values seen are emitted. It optionally also takes an interval (in seconds) if you only want to be updated every so many seconds.

method head

method head(Supply:D: Int(Cool$number = 1 --> Supply:D)

Creates a "head" supply with the same semantics as List.head.

method tail

method tail(Supply:D: Int(Cool$number = 1 --> Supply:D)

Creates a "tail" supply with the same semantics as List.tail.

method rotor

method rotor(Supply:D: @cycle --> Supply:D)

Creates a "rotoring" supply with the same semantics as List.rotor.

method delayed

method delayed(Supply:D: $seconds --> Supply:D)

Creates a new supply in which all values flowing through the given supply are emitted, but with the given delay in seconds.

method throttle

method throttle(Supply:D:
  $limit,                 # values / time or simultaneous processing 
  $seconds or $callable,  # time-unit / code to process simultaneously 
  $delay = 0,             # initial delay before starting, in seconds 
  :$control,              # supply to emit control messages on (optional) 
  :$status,               # supply to tap status messages from (optional) 
  :$bleed,                # supply to bleed messages to (optional) 
  :$vent-at,              # bleed when so many buffered (optional) 
  :$scheduler,            # scheduler to use, default $*SCHEDULER 
  --> Supply:D)

Produces a Supply from a given Supply, but makes sure the number of messages passed through, is limited.

It has two modes of operation: per time-unit or by maximum number of execution of a block of code: this is determined by the second positional parameter.

The first positional parameter specifies the limit that should be applied.

If the second positional parameter is a Callable, then the limit indicates the maximum number of parallel processes executing the Callable, which is given the value that was received. The emitted values in this case will be the Promises that were obtained from starting the Callable.

If the second positional parameter is a numeric value, it is interpreted as the time-unit (in seconds). If you specify .1 as the value, then it makes sure you don't exceed the limit for every tenth of a second.

If the limit is exceeded, then incoming messages are buffered until there is room to pass on / execute the Callable again.

The third positional parameter is optional: it indicates the number of seconds the throttle will wait before passing on any values.

The :control named parameter optionally specifies a Supply that you can use to control the throttle while it is in operation. Messages that can be sent, are strings in the form of "key:value". Please see below for the types of messages that you can send to control the throttle.

The :status named parameter optionally specifies a Supply that will receive any status messages. If specified, it will at least send one status message after the original Supply is exhausted. See status message below.

The :bleed named parameter optionally specifies a Supply that will receive any values that were either explicitly bled (with the bleed control message), or automatically bled (if there's a vent-at active).

The :vent-at named parameter indicates the number of values that may be buffered before any additional value will be routed to the :bleed Supply. Defaults to 0 if not specified (causing no automatic bleeding to happen). Only makes sense if a :bleed Supply has also been specified.

The :scheduler named parameter indicates the scheduler to be used. Defaults to $*SCHEDULER.

control messages

These messages can be sent to the :control Supply. A control message consists of a string of the form "key: value", e.g. "limit: 4".

Change the number of messages (as initially given in the first positional) to the value given.

Route the given number of buffered messages to the :bleed Supply.

Change the maximum number of buffered values before automatic bleeding takes place. If the value is lower than before, will cause immediate rerouting of buffered values to match the new maximum.

Send a status message to the :status Supply with the given id.

status message

The status return message is a hash with the following keys:

The current number of messages / callables that is still allowed to be passed / executed.

The number of messages routed to the :bleed Supply.

The number of messages currently buffered because of overflow.

The number of messages emitted (passed through).

The id of this status message (a monotonically increasing number). Handy if you want to log status messages.

The current limit that is being applied.

The maximum number of messages that may be buffered before they're automatically re-routed to the :bleed Supply.

Examples

Have a simple piece of code announce when it starts running asynchronously, wait a random amount of time, then announce when it is done. Do this 6 times, but don't let more than 3 of them run simultaneously.

my $s = Supply.from-list(^6);  # set up supply 
my $t = $s.throttle: 3,        # only allow 3 at a time 
{                              # code block to run 
    say "running $_";          # announce we've started 
    sleep rand;                # wait some random time 
    say "done $_"              # announce we're done 
}                              # don't need ; because } at end of line 
$t.wait;                       # wait for the supply to be done 

and the result of one run will be:

running 0
running 1
running 2
done 2
running 3
done 1
running 4
done 4
running 5
done 0
done 3
done 5

method stable

method stable(Supply:D: $seconds:$scheduler --> Supply:D)

Creates a new supply that only passes on a value flowing through the given supply if it wasn't superseded by another value in the given time (in seconds). Optionally uses another scheduler than the default scheduler, using the :scheduler parameter.

method reduce

method reduce(Supply:D: &with --> Supply:D)

Creates a "reducing" supply with the same semantics as List.reduce.

method lines

method lines(Supply:D: :$chomp = True --> Supply:D)

Creates a supply that will emit the characters coming in line by line from a supply that's usually created by some asynchronous I/O operation. The optional :chomp parameter indicates whether to remove line separators: the default is True.

method words

method words(Supply:D: --> Supply:D)

Creates a supply that will emit the characters coming in word for word from a supply that's usually created by some asynchronous I/O operation.

method unique

method unique(Supply:D: :$as:$with:$expires --> Supply:D)

Creates a supply that only provides unique values, as defined by the optional :as and :with parameters (same as with List.unique). The optional :expires parameter how long to wait (in seconds) before "resetting" and not considering a value to have been seen, even if it's the same as an old value.

method squish

method squish(Supply:D: :$as:$with:$expires --> Supply:D)

Creates a supply that only provides unique values, as defined by the optional :as and :with parameters (same as with List.squish). The optional :expires parameter how long to wait (in seconds) before "resetting" and not considering a value to have been seen, even if it's the same as an old value.

method max

method max(Supply:D: &by = &infix:<cmp> --> Supply:D)

Creates a supply that only emits values from the given supply if they are larger than any value seen before. In other words, from a continuously ascending supply it will emit all the values. From a continuously descending supply it will only emit the first value. The optional parameter specifies the comparator, just as with Any.max.

method min

method min(Supply:D: &by = &infix:<cmp> --> Supply:D)

Creates a supply that only emits values from the given supply if they are smaller than any value seen before. In other words, from a continuously descending supply it will emit all the values. From a continuously ascending supply it will only emit the first value. The optional parameter specifies the comparator, just as with Any.max.

method minmax

method minmax(Supply:D: &by = &infix:<cmp> --> Supply:D)

Creates a supply that emits a Range every time a new minimum or maximum values is seen from the given supply. The optional parameter specifies the comparator, just as with Any.max.

method start

method start(Supply:D: &startee --> Supply:D)

Creates a supply of supplies. For each value in the original supply, the code object is scheduled on another thread, and returns a supply either of a single value (if the code succeeds), or one that quits without a value (if the code fails).

This is useful for asynchronously starting work that you don't block on.

Use migrate to join the values into a single supply again.

method migrate

method migrate(Supply:D: --> Supply:D)

Creates a supply that acts like the last supply emitted to the given supply of supplies (usually created with start.

Methods that combine supplies

method merge

method merge(Supply @*supplies --> Supply:D)

Creates a supply to which any value seen from the given supplies, is emitted. The resulting supply is done Only when all given supplies are done. Can also be called as a class method.

method zip

method zip(Supply @*supplies:&with = &[,] --> Supply:D)

Creates a supply that emits combined values as soon as there is a new value seen on all of the supplies. By default, Lists are created, but this can be changed by specifying your own combiner with the :with parameter. The resulting supply is done as soon as any of the given supplies are done. Can also be called as a class method.

method zip-latest

method zip-latest(Supply @*supplies:&with = &[,], :$initial --> Supply:D)

Creates a supply that emits combined values as soon as there is a new value seen on any of the supplies. By default, Lists are created, but this can be changed by specifying your own combiner with the :with parameter. The optional :initial parameter can be used to indicate the initial state of the combined values. By default, all supplies have to have at least one value emitted on them before the first combined values is emitted on the resulting supply. The resulting supply is done as soon as any of the given supplies are done. Can also be called as a class method.

I/O features exposed as supplies

sub signal

sub signal(*@signals:$scheduler = $*SCHEDULER)

Creates a supply for the Signal enums (such as SIGINT) specified, and an optional :scheduler parameter. Any signals received, will be emitted on the supply. For example:

signal(SIGINT).tap{ say "Thank you for your attention"exit 0 } );

would catch Control-C, thank you, and then exit.

To go from a signal number to a Signal, you can do something like this:

signal(Signal(2)).tap-> $sig { say "Received signal: $sig" } );

The list of supported signals can be found by checking Signal::.keys (as you would any enum). For more details on how enums work see enum.

method IO::Notification.watch-path

method watch-path($path --> Supply:D)

Creates a supply to which the OS will emit values to indicate changes on the file system for the given path. Also has a shortcut with the watch method on an IO object, like this:

IO::Notification.watch-path(".").act{ say "$^file changed" } );
".".IO.watch.act(                     { say "$^file changed" } );   # same 

Type graph

Type relations for Supply
perl6-type-graph Supply Supply Any Any Supply->Any Mu Mu Any->Mu

Stand-alone image: vector

Routines supplied by class Any

Supply inherits from class Any, which provides the following methods:

(Any) method ACCEPTS

Defined as:

multi method ACCEPTS(Any:D: Mu $other)

Usage:

EXPR.ACCEPTS(EXPR);

Returns True if $other === self (i.e. it checks object identity).

Many built-in types override this for more specific comparisons

(Any) method any

Defined as:

method any(--> Junction:D)

Interprets the invocant as a list and creates an any-Junction from it.

say so 2 == <1 2 3>.any;        # OUTPUT: «True␤» 
say so 5 == <1 2 3>.any;        # OUTPUT: «False␤» 

(Any) method all

Defined as:

method all(--> Junction:D)

Interprets the invocant as a list and creates an all-Junction from it.

say so 1 < <2 3 4>.all;         # OUTPUT: «True␤» 
say so 3 < <2 3 4>.all;         # OUTPUT: «False␤» 

(Any) method one

Defined as:

method one(--> Junction:D)

Interprets the invocant as a list and creates a one-Junction from it.

say so 1 == (123).one;      # OUTPUT: «True␤» 
say so 1 == (121).one;      # OUTPUT: «False␤» 

(Any) method none

Defined as:

method none(--> Junction:D)

Interprets the invocant as a list and creates a none-Junction from it.

say so 1 == (123).none;     # OUTPUT: «False␤» 
say so 4 == (123).none;     # OUTPUT: «True␤» 

(Any) method list

Defined as:

method list(--> List:D)

Interprets the invocant as a list, and returns that List.

say 42.list.^name;           # OUTPUT: «List␤» 
say 42.list.elems;           # OUTPUT: «1␤» 

(Any) method push

Defined as:

method push(|values --> Positional:D)

The method push is defined for undefined invocants and allows for autovivifying undefined to an empty Array, unless the undefined value implements Positional already. The argument provided will then be pushed into the newly created Array.

my %h;
dd %h<a>;      # Any (and therefore undefined) 
%h<a>.push(1); # .push on Any 
dd %h;         # «Hash %h = {:a($[1])}␤» # please note the Array 

(Any) routine reverse

Defined as:

multi sub    reverse(*@list  --> Seq:D)
multi method reverse(List:D: --> Seq:D)

Returns a Seq with the same elements in reverse order.

Note that reverse always refers to reversing elements of a list; to reverse the characters in a string, use flip.

Examples:

say <hello world!>.reverse;     # OUTPUT: «(world! hello)␤» 
say reverse ^10;                # OUTPUT: «(9 8 7 6 5 4 3 2 1 0)␤» 

(Any) method sort

Defined as:

multi method sort()
multi method sort(&by)

Sorts iterables with infix:<cmp> or given code object and returns a new List. Optionally, takes a Callable as a positional parameter, specifying how to sort.

Examples:

say <b c a>.sort;                           # OUTPUT: «(a b c)␤» 
say 'bca'.comb.sort.join;                   # OUTPUT: «abc␤» 
say 'bca'.comb.sort({$^b cmp $^a}).join;    # OUTPUT: «cba␤» 
say '231'.comb.sort(&infix:«<=>»).join;     # OUTPUT: «123␤» 

(Any) method map

Defined as:

multi method map(\SELF: &block;; :$label:$item)
multi method map(HyperIterable:D: &block;; :$label)

map will iterate over the invocant and apply the number of positional parameters of the code object from the invocant per call. The returned values of the code object will become elements of the returned Seq.

The :$label and :$item are useful only internally, since for loops get converted to maps. The :$label takes an existing Label to label the .map's loop with and :$item controls whether the iteration will occur over (SELF,) (if :$item is set) or SELF.

(Any) method deepmap

Defined as:

method deepmap(&block --> Listis nodal

deepmap will apply &block to each element and return a new List with the return values of &block, unless the element does the Iterable role. For those elements deepmap will descend recursively into the sublist.

dd [[1,2,3],[[4,5],6,7]].deepmap(*+1);
# OUTPUT: «[[2, 3, 4], [[5, 6], 7, 8]]␤» 

(Any) method duckmap

Defined as:

method duckmap(&blockis rw is nodal

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

<a b c d e f g>.duckmap(-> $_ where <c d e>.any { .uc }).say;
# OUTPUT: «(a b C D E f g)␤» 
(('d''e'), 'f').duckmap(-> $_ where <e f>.any { .uc }).say;
# OUTPUT: «((d E) F)␤» 

(Any) method flat

Defined as:

method flat(--> Seq:Dis nodal

Interprets the invocant as a list, flattens non-containerized Iterables into a flat list, and returns that list. Keep in mind Map and Hash types are Iterable and so will be flattened into lists of pairs.

say ((12), (3), %(:42a));      # OUTPUT: «((1 2) 3 {a => 42})␤» 
say ((12), (3), %(:42a)).flat# OUTPUT: «(1 2 3 a => 42)␤» 

Note that Arrays containerize their elements by default, and so flat will not flatten them. You can use hyper method call to call .List method on all the inner Iterables and so de-containerize them, so that flat can flatten them:

say [[123], [(45), 67]]      .flat# OUTPUT: «([1 2 3] [(4 5) 6 7])␤» 
say [[123], [(45), 67]]».List.flat# OUTPUT: «(1 2 3 4 5 6 7)␤» 

For more fine-tuned options, see deepmap, duckmap, and signature destructuring

(Any) method eager

Defined as:

method eager(--> Seq:Dis nodal

Interprets the invocant as a list, evaluates it eagerly, and returns that list.

say (1..10).eager;              # OUTPUT: «(1 2 3 4 5 6 7 8 9 10)␤» 

(Any) method elems

Defined as:

method elems(--> Int:Dis nodal

Interprets the invocant as a list, and returns the number of elements in the list.

say 42.elems;                   # OUTPUT: «1␤» 
say <a b c>.elems;              # OUTPUT: «3␤» 

(Any) method end

method end(--> Any:Dis nodal

Interprets the invocant as a list, and returns the last index of that list.

say 6.end;                      # OUTPUT: «0␤» 
say <a b c>.end;                # OUTPUT: «2␤» 

(Any) method pairup

Defined as:

method pairup(--> Seq:Dis nodal

Interprets the invocant as a list, and constructs a list of pairs from it, in the same way that assignment to a Hash does. That is, it takes two consecutive elements and constructs a pair from them, unless the item in the key position already is a pair (in which case the pair is passed is passed through, and the next list item, if any, is considered to be a key again).

say (=> 1'b''c').pairup.perl;     # OUTPUT: «(:a(1), :b("c")).Seq␤» 

(Any) sub exit

Defined as:

sub exit(Int() $status = 0)

Exits the current process with return code $status.

(Any) sub item

Defined as:

proto sub item(|) is pure
multi sub item(\x)
multi sub item(|c)
multi sub item(Mu $a)

Forces given object to be evaluated in item context and returns the value of it.

say item([1,2,3]).perl;              # OUTPUT: «$[1, 2, 3]␤» 
say item({ apple => 10 }).perl;      # OUTPUT: «${:apple(10)}␤» 
say item("abc").perl;                # OUTPUT: «"abc"␤» 

You can also use $ as item contextualizer.

say $[1,2,3].perl;                   # OUTPUT: «$[1, 2, 3]␤» 
say $("abc").perl;                   # OUTPUT: «"abc"␤» 

(Any) method Array

Defined as:

method Array(--> Array:Dis nodal

Coerce the invocant to Array.

(Any) method List

Defined as:

method List(--> List:Dis nodal

Coerce the invocant to List.

(Any) method Hash

Defined as:

method Hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method hash

Defined as:

method hash(--> Hash:Dis nodal

Coerce the invocant to Hash.

(Any) method Slip

Defined as:

method Slip(--> Slip:Dis nodal

Coerce the invocant to Slip.

(Any) method Map

Defined as:

method Map(--> Map:Dis nodal

Coerce the invocant to Map.

(Any) method Bag

Defined as:

method Bag(--> Bag:Dis nodal

Coerce the invocant to Bag, whereby Positionals are treated as lists of values.

(Any) method BagHash

Defined as:

method BagHash(--> BagHash:Dis nodal

Coerce the invocant to BagHash, whereby Positionals are treated as lists of values.

(Any) method Set

Defined as:

method Set(--> Set:Dis nodal

Coerce the invocant to Set, whereby Positionals are treated as lists of values.

(Any) method SetHash

Defined as:

method SetHash(--> SetHash:Dis nodal

Coerce the invocant to SetHash, whereby Positionals are treated as lists of values.

(Any) method Mix

Defined as:

method Mix(--> Mix:Dis nodal

Coerce the invocant to Mix, whereby Positionals are treated as lists of values.

(Any) method MixHash

Defined as:

method MixHash(--> MixHash:Dis nodal

Coerce the invocant to MixHash, whereby Positionals are treated as lists of values.

(Any) method Supply

Defined as:

method Supply(--> Supply:Dis nodal

Coerce the invocant first to a List and then to a Supply.

(Any) method min

Defined As:

multi method min(--> Any:D)
multi method min(&by --> Any:D)

Coerces to Iterable and returns the numerically smallest element. If a Callable positional argument is provided it is called with each element and its smallest return values is returned.

(Any) method max

Defined As:

multi method max(--> Any:D)
multi method max(&by --> Any:D)

Coerces to Iterable and returns the numerically biggest element. If a Callable positional argument is provided it is called with each element and its biggest return values is returned.

(Any) method minmax

Defined As:

multi method minmax(--> List:D)
multi method minmax(&by --> List:D)

Returns a list containing the smallest and the biggest element. If a Callable positional argument is provided each element is filtered and then numerically compared.

(Any) method minpairs

Defined As:

multi method minpairs(Any:D: --> Seq:D)

Calls .pairs and returns a Seq with all of the Pairs with minimum values, as judged by the cmp operator:

<a b c a b c>.minpairs.perl.put# OUTPUT: «(0 => "a", 3 => "a").Seq␤» 
%(:42a, :75b).minpairs.perl.put# OUTPUT: «(:a(42),).Seq␤» 

(Any) method maxpairs

Defined As:

multi method maxpairs(Any:D: --> Seq:D)

Calls .pairs and returns a Seq with all of the Pairs with maximum values, as judged by the cmp operator:

<a b c a b c>.maxpairs.perl.put# OUTPUT: «(2 => "c", 5 => "c").Seq␤» 
%(:42a, :75b).maxpairs.perl.put# OUTPUT: «(:b(75),).Seq␤» 

(Any) method sum

Defined As:

    method sum(--> TODO)

TODO

(Any) method keys

Defined As:

    method keys(--> TODO)

TODO

(Any) method flatmap

Defined As:

    method flatmap(--> TODO)

TODO

(Any) method roll

Defined As:

    method roll(--> TODO)

TODO

(Any) method pick

Defined As:

    method pick(--> TODO)

TODO

(Any) method head

Defined As:

    method head(--> TODO)

TODO

(Any) method tail

Defined As:

    method tail(--> TODO)

TODO

(Any) method skip

Defined As:

    method skip(--> TODO)

TODO

(Any) method prepend

Defined As:

    method prepend(--> TODO)

TODO

(Any) method unshift

Defined As:

    method unshift(--> TODO)

TODO

(Any) method first

Defined As:

    method first(--> TODO)

TODO

(Any) method unique

Defined As:

    method unique

Treats the Any as a 1-item list and uses List.unique on it.

(Any) method repeated

Defined As:

    method repeated(--> TODO)

TODO

(Any) method squish

Defined As:

    method squish(--> TODO)

TODO

(Any) method reduce

Defined As:

    method reduce(--> TODO)

TODO

(Any) method permutations

Defined As:

    method permutations(--> TODO)

TODO

(Any) method categorize

Defined As:

    method categorize(--> TODO)

TODO

(Any) method classify

Defined As:

    method classify(--> TODO)

TODO

(Any) method produce

Defined As:

    method produce(--> TODO)

TODO

(Any) method rotor

Defined As:

    method rotor(--> TODO)

TODO

(Any) method pairs

Defined As:

    method pairs(--> TODO)

TODO

(Any) method antipairs

Defined As:

    method antipairs(--> TODO)

TODO

(Any) method kv

Defined As:

    method kv(--> TODO)

TODO

(Any) method tree

Defined As:

    method tree(--> TODO)

TODO

(Any) method nl-out

Defined As:

    method nl-out(--> TODO)

TODO

(Any) method invert

Defined As:

    method invert(--> TODO)

TODO

(Any) method combinations

Defined As:

    method combinations(--> TODO)

TODO

(Any) method print-nl

Defined As:

    method print-nl(--> TODO)

TODO

(Any) method nodemap

Defined As:

    method nodemap(--> TODO)

TODO

(Any) method iterator

Defined As:

    method iterator(--> TODO)

TODO

(Any) method grep

Defined As:

    method grep(--> TODO)

TODO

(Any) method match

Defined As:

    method match(--> TODO)

TODO

(Any) method append

Defined As:

    method append(--> TODO)

TODO

(Any) method join

Defined As:

    method join(--> TODO)

TODO

(Any) method values

Defined As:

    method values(--> TODO)

TODO

(Any) method collate

Defined As:

    method collate(--> TODO)

TODO

(Any) method batch

Defined As:

    method batch(--> TODO)

TODO

(Any) method cache

Defined As:

    method cache(--> TODO)

TODO

Routines supplied by class Mu

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

(Mu) routine defined

multi sub    defined(Mu --> Bool:D)
multi method defined(   --> Bool:D)

Returns False on the type object, and True otherwise.

say Int.defined;                # OUTPUT: «False␤» 
say 42.defined;                 # OUTPUT: «True␤» 

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

sub fails() { fail 'oh noe' };
say fails().defined;            # OUTPUT: «False␤» 

(Mu) routine isa

multi method isa(Mu $type     --> Bool:D)
multi method isa(Str:D $type  --> Bool:D)

Returns True if the invocant is an instance of class $type, a subset type or a derived class (through inheritance) of $type.

my $i = 17;
say $i.isa("Int");   # OUTPUT: «True␤» 
say $i.isa(Any);     # OUTPUT: «True␤» 

A more idiomatic way to do this is to use the smartmatch operator ~~ instead.

my $s = "String";
say $s ~~ Str;       # OUTPUT: «True␤» 

(Mu) routine does

method does(Mu $type --> Bool:D)

Returns True if and only if the invocant conforms to type $type.

my $d = Date.new('2016-06-03');
say $d.does(Dateish);             # True    (Date does role Dateish) 
say $d.does(Any);                 # True    (Date is a subclass of Any) 
say $d.does(DateTime);            # False   (Date is not a subclass of DateTime) 

Using the smart match operator ~~ is a more idiomatic alternative.

my $d = Date.new('2016-06-03');
say $d ~~ Dateish;                # OUTPUT: «True␤» 
say $d ~~ Any;                    # OUTPUT: «True␤» 
say $d ~~ DateTime;               # OUTPUT: «False␤» 

(Mu) routine Bool

multi sub    Bool(Mu --> Bool:D)
multi method Bool(   --> 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;                    # OUTPUT: «False␤» 
say Mu.new.Bool;                # OUTPUT: «True␤» 
say [123].Bool;             # OUTPUT: «True␤» 
say [].Bool;                    # OUTPUT: «False␤» 
say { 'hash' => 'full' }.Bool;  # OUTPUT: «True␤» 
say {}.Bool;                    # OUTPUT: «False␤» 
say "".Bool;                    # OUTPUT: «False␤» 
say 0.Bool;                     # OUTPUT: «False␤» 
say 1.Bool;                     # OUTPUT: «True␤» 
say "0".Bool;                   # OUTPUT: «True␤» 

(Mu) method Str

multi method Str(--> 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. 

(Mu) routine gist

multi sub    gist(+args --> Str)
multi method gist(   --> Str)

Returns a string representation of the invocant, optimized for fast recognition by humans. As such lists will be truncated at 100 elements. Use .perl to get all elements.

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 that may truncate output.

gist is the method that say calls implicitly, for non-Str types, so say $something and say $something.gist generally produce the same output.

say Mu.gist;        # OUTPUT: «(Mu)␤» 
say Mu.new.gist;    # OUTPUT: «Mu.new␤» 

(Mu) routine perl

multi sub    perl(Mu --> Str)
multi method perl(   --> 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

(Mu) method item

method item(Mu \item:is raw

Forces the invocant to be evaluated in item context and returns the value of it.

say [1,2,3].item.perl;         # OUTPUT: «$[1, 2, 3]␤» 
say { apple => 10 }.item.perl# OUTPUT: «${:apple(10)}␤» 
say "abc".item.perl;           # OUTPUT: «"abc"␤» 

(Mu) method self

method self(--> Mu)

Returns the object it is called on.

(Mu) method clone

method clone(*%twiddles)

Creates a shallow clone of the invocant. Alternative values for public attributes can be provided via named arguments with names matching the attributes' names.

class Point2D {
    has ($.x$.y);
    multi method gist(Point2D:D:{
        "Point($.x$.y)";
    }
}
 
my $p = Point2D.new(x => 2=> 3);
 
say $p;                     # OUTPUT: «Point(2, 3)␤» 
say $p.clone(=> -5);      # OUTPUT: «Point(2, -5)␤» 

(Mu) 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.

(Mu) method bless

method bless(*%attrinit --> 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(-11);

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

(Mu) method CREATE

method CREATE(--> Mu:D)

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

say Mu.CREATE.defined;  # OUTPUT: «True␤» 

(Mu) method print

multi method print(--> Bool:D)

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

"abc\n".print;          # RESULT: «abc␤» 

(Mu) method put

multi method put(--> Bool:D)

Prints value to $*OUT, adding a newline at end, and if necessary, stringifying non-Str object using the .Str method.

"abc".put;              # RESULT: «abc␤» 

(Mu) method say

multi method say(--> Bool:D)

Prints value to $*OUT after stringification using .gist method with newline at end. To produce machine readable output use .put.

say 42;                 # OUTPUT: «42␤» 

(Mu) 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;           # OUTPUT: «True␤» 
say 42 ~~ Int;          # OUTPUT: «True␤» 
say 42 ~~ Str;          # OUTPUT: «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.

(Mu) method WHICH

multi method WHICH(--> 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;       # OUTPUT: «True␤» 

(Mu) method WHERE

method WHERE(--> Int)

Returns an Int representing the memory address of the object.

(Mu) 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.

(Mu) 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.

See Exporting and Selective Importing Modules for more details.

(Mu) method return

method return()

The method return will stop execution of a subroutine or method, run all relevant phasers and provide invocant as a return value to the caller. If a return type constraint is provided it will be checked unless the return value is Nil. A control exception is raised and can be caught with CONTROL.

sub f { (1|2|3).return };
dd f(); # OUTPUT: «any(1, 2, 3)␤» 

(Mu) method return-rw

Same as method return except that return-rw returns a writable container to the invocant (see more details here: return-rw).

(Mu) method emit

method emit()

Emits the invocant into the enclosing supply or react block.

react { whenever supply { .emit for "foo"42.5 } {
    say "received {.^name} ($_)";
}}
 
# OUTPUT: 
# received Str (foo) 
# received Int (42) 
# received Rat (0.5) 

(Mu) method take

method take()

Returns the invocant in the enclosing gather block.

sub insert($sep+@list{
    gather for @list {
        FIRST .takenext;
        take slip $sep.item
    }
}
 
say insert ':', <a b c>;
# OUTPUT: «(a : b : c)␤» 

(Mu) routine take

sub take(\item)

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;    # six random values 

(Mu) routine take-rw

sub take-rw(\item)

Returns the given item to the enclosing gather block, without introducing a new container.

my @a = 1...3;
sub f(@list){ gather for @list { take-rw $_ } };
for f(@a{ $_++ };
say @a;
# OUTPUT: «[2 3 4]␤» 

(Mu) 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(@argseq '-v' | '-V';
if $verbose-selected.so {
    say "Verbose option detected in arguments";
} # OUTPUT: «Verbose option detected in arguments␤» 

(Mu) 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(@argseq '-v' | '-V';
if $verbose-selected.not {
    say "Verbose option not present in arguments";
} # OUTPUT: «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(@argseq '-v' | '-V';
if not $verbose-selected {
    say "Verbose option not present in arguments";
} # OUTPUT: «Verbose option not present in arguments␤»