is Mu
While Mu
is the root of the Raku class hierarchy, Any
is the class that serves as a default base class for new classes, and as the base class for most built-in classes.
Since Raku intentionally confuses items and single-element lists, most methods in Any
are also present on class List
, and coerce to List or a list-like type.
Methods§
method ACCEPTS§
multi method ACCEPTS(Any: Mu )
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.
method any§
method any(--> Junction)
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»
method all§
method all(--> Junction)
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»
method one§
method one(--> Junction)
Interprets the invocant as a list and creates a one-Junction
from it.
say so 1 == (1, 2, 3).one; # OUTPUT: «True»say so 1 == (1, 2, 1).one; # OUTPUT: «False»
method none§
method none(--> Junction)
Interprets the invocant as a list and creates a none-Junction
from it.
say so 1 == (1, 2, 3).none; # OUTPUT: «False»say so 4 == (1, 2, 3).none; # OUTPUT: «True»
method list§
multi method list(Any:)multi method list(Any \SELF:)
Applies the infix ,
operator to the invocant and returns the resulting List
:
say 42.list.^name; # OUTPUT: «List»say 42.list.elems; # OUTPUT: «1»
Subclasses of Any
may choose to return any core type that does the Positional
role from .list
. Use .List
to coerce specifically to List
.
@
can also be used as a list or Positional
contextualizer:
my = $[1,2,3];say .raku; # OUTPUT: «$[1, 2, 3]»my = @;say .^name; # OUTPUT: «Array»
In the first case, the list is itemized. @
as a prefix puts the initial scalar in a list context by calling .list
and turning it into an Array
.
method push§
multi method push(Any \SELF: |values --> Positional)
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 ;say <a>; # OUTPUT: «(Any)» <-- Undefined<a>.push(1); # .push on Anysay ; # OUTPUT: «{a => [1]}» <-- Note the Array
routine reverse§
multi reverse(* --> Seq)multi method reverse(List: --> Seq)
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)»
method sort§
multi method sort()multi method sort()
Sorts iterables with cmp or given code object and returns a new Seq
. 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().join; # OUTPUT: «cba»say '231'.comb.sort(:«<=>»).join; # OUTPUT: «123»sub by-character-countsay <Let us impart what we have seen tonight unto young Hamlet>.sort();# OUTPUT: «(us we Let what have seen unto young impart Hamlet tonight)»
routine map§
multi method map(\SELF: )multi map(, +values)
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 map
s. 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
.
In sub
form, it will apply the code
block to the values
, which will be used as invocant.
The forms with |c
, Iterable:D \iterable
and Hash:D \hash
as signatures will fail with X::Cannot::Map
, and are mainly meant to catch common traps.
Inside a for
statement that has been sunk, a Seq
created by a map will also sink:
say gather for 1# OUTPUT: «(0 1 2)»
In this case, gather
sinks the for
statement, and the result of sinking the Seq
will be iterating over its elements, calling .take
on them.
method deepmap§
method deepmap( --> List) is 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.
say [[1,2,3],[[4,5],6,7]].deepmap(* + 1);# OUTPUT: «[[2 3 4] [[5 6] 7 8]]»
In the case of Associative
s, it will be applied to its values:
.deepmap( *.flip ).say# OUTPUT: «{a => (laer tsil), this => gniht, what => si}»
method duckmap§
method duckmap() is rw is nodal
duckmap
will apply &block
on each element that behaves in such a way that &block
can be applied. If it fails, it will descend recursively if possible, or otherwise return the item without any transformation. It will act on values if the object is Associative
.
<a b c d e f g>.duckmap(-> where <c d e>.any ).say;# OUTPUT: «(a b C D E f g)»(('d', 'e'), 'f').duckmap(-> where <e f>.any ).say;# OUTPUT: «((d E) F)».duckmap(-> where <e f>.any ).say;# OUTPUT: «{first => (d E), second => F}»
In the first case, it is applied to c
, d
and e
which are the ones that meet the conditions for the block ({ .uc }
) to be applied; the rest are returned as is.
In the second case, the first item is a list that does not meet the condition, so it's visited; that flat list will behave in the same way as the first one. In this case:
say [[1,2,3],[[4,5],6,7]].duckmap( *² ); # OUTPUT: «[9 9]»
You can square anything as long as it behaves like a number. In this case, there are two arrays with 3 elements each; these arrays will be converted into the number 3 and squared. In the next case, however
say [[1,2,3],[[4,5],6.1,7.2]].duckmap( -> Rat );# OUTPUT: «[[1 2 3] [[4 5] 37.21 51.84]]»
3-item lists are not Rat
, so it descends recursively, but eventually only applies the operation to those that walk (or slither, as the case may be) like a Rat
.
Although on the surface (and name), duckmap
might look similar to deepmap
, the latter is applied recursively regardless of the type of the item.
method nodemap§
method nodemap( --> List) is nodal
nodemap
will apply &block
to each element and return a new List
with the return values of &block
. In contrast to deepmap it will not descend recursively into sublists if it finds elements which do the Iterable
role.
say [[1,2,3], [[4,5],6,7], 7].nodemap(*+1);# OUTPUT: «(4, 4, 8)»say [[2, 3], [4, [5, 6]]]».nodemap(*+1)# OUTPUT: «((3 4) (5 3))»
The examples above would have produced the exact same results if we had used map instead of nodemap
. The difference between the two lies in the fact that map flattens out Slip
s while nodemap
doesn't.
say [[2,3], [[4,5],6,7], 7].nodemap();# OUTPUT: «(() () 7)»say [[2,3], [[4,5],6,7], 7].map();# OUTPUT: «(7)»
When applied to Associative
s, it will act on the values:
.nodemap( *.flip ).say;# OUTPUT: «{this => gniht, what => si}»
method flat§
method flat() is nodal
Interprets the invocant as a list, flattens non-containerized Iterable
s 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 ((1, 2), (3), %(:42a)); # OUTPUT: «((1 2) 3 {a => 42})»say ((1, 2), (3), %(:42a)).flat; # OUTPUT: «(1 2 3 a => 42)»
Note that Array
s containerize their elements by default, and so flat
will not flatten them. You can use the
hyper method call to call the .List
method on all the inner Iterable
s and so de-containerize them, so that flat
can flatten them:
say [[1, 2, 3], [(4, 5), 6, 7]] .flat; # OUTPUT: «([1 2 3] [(4 5) 6 7])»say [[1, 2, 3], [(4, 5), 6, 7]]».List.flat; # OUTPUT: «(1 2 3 4 5 6 7)»
For more fine-tuned options, see deepmap, duckmap, and signature destructuring
method eager§
method eager() is nodal
Interprets the invocant as a List
, evaluates it eagerly, and returns that List
.
my = 1..5;say ; # OUTPUT: «1..5»say .eager; # OUTPUT: «(1 2 3 4 5)»
method elems§
multi method elems(Any: --> 1)multi method elems(Any:)
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»say Whatever.elems ; # OUTPUT: «1»
It will also return 1 for classes.
method end§
multi method end(Any: --> 0)multi method end(Any:)
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»
method pairup§
multi method pairup(Any:)multi method pairup(Any:)
Returns an empty Seq
if the invocant is a type object
Range.pairup.say; # OUTPUT: «()»
Interprets the invocant as a list, and constructs a list of Pair
s 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 through, and the next list item, if any, is considered to be a key again). It returns a Seq
of Pair
s.
say (a => 1, 'b', 'c').pairup.raku; # OUTPUT: «(:a(1), :b("c")).Seq»
sub item§
multi item(\x)multi item(|c)multi item(Mu )
Forces given object to be evaluated in item context and returns the value of it.
say item([1,2,3]).raku; # OUTPUT: «$[1, 2, 3]»say item( %( apple => 10 ) ).raku; # OUTPUT: «${:apple(10)}»say item("abc").raku; # OUTPUT: «"abc"»
You can also use $
as item contextualizer.
say $[1,2,3].raku; # OUTPUT: «$[1, 2, 3]»say $("abc").raku; # OUTPUT: «"abc"»
method Array§
method Array(--> Array) is nodal
Coerces the invocant to an Array
.
method List§
method List(--> List) is nodal
Coerces the invocant to List
, using the list method.
method serial§
multi method serial()
This method is Rakudo specific, and is not included in the Raku spec.
The method returns the self-reference to the instance itself:
my ; # defaults to Anysay .serial.^name; # OUTPUT: «Any»say .^name; # OUTPUT: «Any»my = 'food';.serial.say; # OUTPUT: «food»
This is apparently a no-op, as exemplified by the third example above. However, in HyperSeq
s and RaceSeq
s it returns a serialized Seq
, so it can be considered the opposite of the hyper/race
methods. As such, it ensures that we are in serial list-processing mode, as opposed to the autothreading mode of those methods.
method Hash§
multi method Hash( --> Hash)
Coerces the invocant to Hash
.
method hash§
multi method hash(Any:)multi method hash(Any:)
When called on a type object, returns an empty Hash
. On instances, it is equivalent to assigning the invocant to a %-
sigiled variable and returning that.
Subclasses of Any
may choose to return any core type that does the Associative
role from .hash
. Use .Hash
to coerce specifically to Hash
.
my ; # $d is Anysay .hash; # OUTPUT: {}my is Map = a => 42, b => 666;say .hash; # OUTPUT: «Map.new((a => 42, b => 666))»say .Hash; # OUTPUT: «{a => 42, b => 666}»
method Slip§
method Slip(--> Slip) is nodal
Coerces the invocant to Slip
.
method Map§
method Map(--> Map) is nodal
Coerces the invocant to Map
.
method Seq§
method Seq() is nodal
Coerces the invocant to Seq
.
method Bag§
method Bag(--> Bag) is nodal
Coerces the invocant to Bag
, whereby Positional
s are treated as lists of values.
method BagHash§
method BagHash(--> BagHash) is nodal
Coerces the invocant to BagHash
, whereby Positional
s are treated as lists of values.
method Set§
method Set(--> Set) is nodal
Coerces the invocant to Set
, whereby Positional
s are treated as lists of values.
method SetHash§
method SetHash(--> SetHash) is nodal
Coerces the invocant to SetHash
, whereby Positional
s are treated as lists of values.
method Mix§
method Mix(--> Mix) is nodal
Coerces the invocant to Mix
, whereby Positional
s are treated as lists of values.
method MixHash§
method MixHash(--> MixHash) is nodal
Coerces the invocant to MixHash
, whereby Positional
s are treated as lists of values.
method Supply§
method Supply(--> Supply) is nodal
First, it coerces the invocant to a list
by applying its .list
method, and then to a Supply
.
routine min§
multi method min(?, :, :, :, : )multi min(+args, :, :, :, :, :)
Coerces the invocant to Iterable
and returns the smallest element using cmp semantics; in the case of Map
s and Hash
es, it returns the Pair
with the lowest value.
A Callable
positional argument can be given to the method
form. If that Callable
accepts a single argument, then it will be used to convert the values to be sorted before doing comparisons. The original value is still the one returned from min
.
If that Callable
accepts two arguments, it will be used as the comparator instead of cmp
.
In sub
form, the invocant is passed as an argument and any Callable
must be specified with the named argument :by
.
say (1,7,3).min(); # OUTPUT: «1»say (1,7,3).min(); # OUTPUT: «7»say min(1,7,3); # OUTPUT: «1»say min(1,7,3,:by( )); # OUTPUT: «7»min( %(a => 3, b=> 7 ) ).say ; # OUTPUT: «a => 3»
As of the 2023.08 Rakudo compiler release, additional named arguments can be specified to get all possible information related to the lowest value. Whenever any of these named arguments is specified, the returned value will always be a List
.
:k
Returns a List
with the indices of the lowest values found.
:v
Returns a List
with the actual values of the lowest values found. In the case of a Map
or Hash
, these would the Pair
s.
:kv
Returns a List
with the index and the value alternating.
:p
Returns a List
of Pair
s in which the key is the index value, and the value is the actual lowest value (which in the case of a Map
or a Hash
would be a Pair
).
say <a b c a>.min(:k); # OUTPUT:«(0 3)»say <a b c a>.min(:v); # OUTPUT:«(a a)»say <a b c a>.min(:kv); # OUTPUT:«(0 a 3 a)»say <a b c a>.min(:p); # OUTPUT:«(0 => a 3 => a)»
routine max§
multi method max(?, :, :, :, : )multi max(+args, :, :, :, :, :)
The interface of the max
method / routine is the same as the one of min. But instead of the lowest value, it will return the highest value.
say (1,7,3).max(); # OUTPUT: «7»say (1,7,3).max(); # OUTPUT: «1»say max(1,7,3,:by( )); # OUTPUT: «1»say max(1,7,3); # OUTPUT: «7»max( %(a => 'B', b=> 'C' ) ).say; # OUTPUT: «b => C»
As of the 2023.08 Rakudo compiler release:
say <a b c c>.max(:k); # OUTPUT:«(2 3)»say <a b c c>.max(:v); # OUTPUT:«(c c)»say <a b c c>.max(:kv); # OUTPUT:«(2 c 3 c)»say <a b c c>.max(:p); # OUTPUT:«(2 => c 3 => c)»
routine minmax§
multi method minmax()multi method minmax()multi minmax(+args, :!)multi minmax(+args)
Returns a Range
from the smallest to the largest element.
If a Callable
positional argument is provided, each value is passed into the filter, and its return value is compared instead of the original value. The original values are still used in the returned Range
.
In sub
form, the invocant is passed as an argument and a comparison Callable
can be specified with the named argument :by
.
say (1,7,3).minmax(); # OUTPUT:«1..7»say (1,7,3).minmax(); # OUTPUT:«7..1»say minmax(1,7,3); # OUTPUT: «1..7»say minmax(1,7,3,:by( -* )); # OUTPUT: «7..1»
method minpairs§
multi method minpairs(Any:)
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.raku.put; # OUTPUT: «(0 => "a", 3 => "a").Seq»%(:42a, :75b).minpairs.raku.put; # OUTPUT: «(:a(42),).Seq»
method maxpairs§
multi method maxpairs(Any:)
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.raku.put; # OUTPUT: «(2 => "c", 5 => "c").Seq»%(:42a, :75b).maxpairs.raku.put; # OUTPUT: «(:b(75),).Seq»
method keys§
multi method keys(Any: --> List)multi method keys(Any: --> List)
For defined Any
returns its keys after calling list
on it, otherwise calls list
and returns it.
my = Set(<Þor Oðin Freija>);say .keys; # OUTPUT: «(Þor Oðin Freija)»
See also List.keys
.
Trying the same on a class will return an empty list, since most of them don't really have keys.
method flatmap§
method flatmap(, :)
Convenience method, analogous to .map(&block)
.flat
.
method roll§
multi method roll(--> Any)multi method roll( --> Seq)
Coerces the invocant to a list
by applying its .list
method and uses List.roll
on it.
my Mix = ("þ" xx 3, "ð" xx 4, "ß" xx 5).Mix;say .roll; # OUTPUT: «ð»say .roll(5); # OUTPUT: «(ß ß þ ß þ)»
$m
, in this case, is converted into a list and then a (weighted in this case) dice is rolled on it. See also List.roll
for more information.
method iterator§
multi method iterator(Any:)
Returns the object as an iterator after converting it to a list. This is the function called from the for
statement.
.say for 3; # OUTPUT: «3»
Most subclasses redefine this method for optimization, so it's mostly types that do not actually iterate the ones that actually use this implementation.
method pick§
multi method pick(--> Any)multi method pick( --> Seq)
Coerces the invocant to a List
by applying its .list
method and uses List.pick
on it.
my Range = 'α'..'ω';say .pick(3); # OUTPUT: «(β α σ)»
routine skip§
multi method skip()multi method skip(Whatever)multi method skip(Callable )multi method skip(Int() )multi method skip(, )
Creates a Seq
from 1-item list's iterator and uses Seq.skip
on it, please check that document for real use cases; calling skip
without argument is equivalent to skip(1)
.
multi skip(\skipper, +values)
As of release 2022.07 of the Rakudo compiler, there is also a "sub" version of skip
. It must have the skip specifier as the first argument. The rest of the arguments are turned into a Seq
and then have the skip
method called on it.
method are§
multi method are(Any:)multi method are(Any: Any )
The argumentless version available as of release 2022.02 of the Rakudo compiler. The version with the type argument is in the 6.e language version (early implementation exists in Rakudo compiler 2024.05+).
If called without arguments, returns the strictest type (or role) to which all elements of the list will smartmatch. Returns Nil
on an empty list.
say (1,2,3).are; # OUTPUT: «(Int)»say <a b c>.are; # OUTPUT: «(Str)»say <42 666>.are; # OUTPUT: «(IntStr)»say (42,666e0).are; # OUTPUT: «(Real)»say (42,i).are; # OUTPUT: «(Numeric)»say ("a",42,3.14).are; # OUTPUT: «(Cool)»say ().are; # OUTPUT: «Nil»
Scalar values are interpreted as a single element list.
say 42.are; # OUTPUT: «(Int)»say Int.are; # OUTPUT: «(Int)»
Hashes will be interpreted as a list of pairs, and as such will always produce the Pair
type object. Use the .keys
or .values
method to get the strictest type of the keys or the values of a hash.
my = a => 42, b => "bar";say .keys.are; # OUTPUT: «(Str)»say .values.are; # OUTPUT: «(Cool)»
If called with a type argument, will check if all types in the invocant smartmatch with the given type. If so, returns True
. If any of the smartmatches fails, returns a Failure
.
say (1,2,3).are(Int); # OUTPUT: «True»say <a b c>.are(Str); # OUTPUT: «True»say <42 666>.are(Int); # OUTPUT: «True»say <42 666>.are(Str); # OUTPUT: «True»say (42,666e0).are(Real); # OUTPUT: «True»say (42,i).are(Numeric); # OUTPUT: «True»say ("a",42,3.14).are(Cool); # OUTPUT: «True»say ().are; # OUTPUT: «True»Int.are(Str); # OUTPUT: «Expected 'Str' but got 'Int'»(1,2,3).are(Str); # OUTPUT: «Expected 'Str' but got 'Int' in element 0»
method prepend§
multi method prepend(Any: --> Array)multi method prepend(Any: --> Array)
Called with no arguments on an empty variable, it initializes it as an empty Array
; if called with arguments, it creates an array and then applies Array.prepend
on it.
my ;say .prepend; # OUTPUT: «[]»say ; # OUTPUT: «[]»my ;say .prepend(1,2,3); # OUTPUT: «[1 2 3]»
method unshift§
multi method unshift(Any: --> Array)multi method unshift(Any: --> Array)
Initializes Any
variable as empty Array
and calls Array.unshift
on it.
my ;say .unshift; # OUTPUT: «[]»say ; # OUTPUT: «[]»my ;say .unshift([1,2,3]); # OUTPUT: «[[1 2 3]]»
routine first§
multi method first(Bool )multi method first(Regex , :, *)multi method first(Callable , :, * is copy)multi method first(Mu , :, *)multi method first(:, *)multi first(Bool , |)multi first(Mu , +values, *)
In general, coerces the invocant to a list
by applying its .list
method and uses List.first
on it.
However, this is a multi with different signatures, which are implemented with (slightly) different behavior, although using it as a subroutine is equivalent to using it as a method with the second argument as the object.
For starters, using a Bool
as the argument will always return a Failure
. The form that uses a $test
will return the first element that smartmatches it, starting from the end if :end
is used.
say (3..33).first; # OUTPUT: «3»say (3..33).first(:end); # OUTPUT: «33»say (⅓,⅔…30).first( 0xF ); # OUTPUT: «15»say first 0xF, (⅓,⅔…30); # OUTPUT: «15»say (3..33).first( /\d\d/ ); # OUTPUT: «10»
The third and fourth examples use the Mu $test
forms which smartmatches and returns the first element that does. The last example uses as a test a regex for numbers with two figures, and thus the first that meets that criterion is number 10. This last form uses the Callable
multi:
say (⅓,⅔…30).first( * %% 11, :end, :kv ); # OUTPUT: «(65 22)»
Besides, the search for first will start from the :end
and returns the set of key/values in a list; the key in this case is simply the position it occupies in the Seq
. The :kv
argument, which is part of the %a
argument in the definitions above, modifies what first
returns, providing it as a flattened list of keys and values; for a listy object, the key will always be the index.
From version 6.d, the test can also be a Junction
:
say (⅓,⅔…30).first( 3 | 33, :kv ); # OUTPUT: «(8 3)»
method unique§
multi method unique()multi method unique( :!, :! )multi method unique( :! )multi method unique( :! )
Creates a sequence of unique elements either of the object or of values
in the case it's called as a sub
.
<1 2 2 3 3 3>.unique.say; # OUTPUT: «(1 2 3)»say unique <1 2 2 3 3 3>; # OUTPUT: «(1 2 3)»
The :as
and :with
parameters receive functions that are used for transforming the item before checking equality, and for checking equality, since by default the ===
operator is used:
("1", 1, "1 ", 2).unique( as => Int, with => &[==] ).say; # OUTPUT: «(1 2)»
Please see unique
for additional examples that use its sub form.
method repeated§
multi method repeated()multi method repeated( :!, :! )multi method repeated( :! )multi method repeated( :! )
Similarly to unique
, finds repeated elements in values
(as a routine) or in the object, using the :as
associative argument as a normalizing function and :with
as equality function.
<1 -1 2 -2 3>.repeated(:as(),:with(&[==])).say; # OUTPUT: «(-1 -2)»(3+3i, 3+2i, 2+1i).repeated(as => *.re).say; # OUTPUT: «(3+2i)»
It returns the last repeated element before normalization, as shown in the example above. See repeated
for more examples that use its sub form.
method squish§
multi method squish( :!, : = &[===] )multi method squish( : = &[===] )
Similar to .repeated
, returns the sequence of first elements of contiguous sequences of equal elements, after normalization by the function :as
, if present, and using as an equality operator the :with
argument or ===
by default.
"aabbccddaa".comb.squish.say; # OUTPUT: «(a b c d a)»"aABbccdDaa".comb.squish( :as() ).say; # OUTPUT: «(a B c d a)»(3+2i,3+3i,4+0i).squish( as => *.re, with => &[==]).put; # OUTPUT: «3+2i 4+0i»
As shown in the last example, a sequence can contain a single element. See squish
for additional sub
examples.
method permutations§
method permutations(|c)
Coerces the invocant to a list
by applying its .list
method and uses List.permutations
on it.
say <a b c>.permutations;# OUTPUT: «((a b c) (a c b) (b a c) (b c a) (c a b) (c b a))»say set(1,2).permutations;# OUTPUT: «((2 => True 1 => True) (1 => True 2 => True))»
Permutations of data structures with a single or no element will return a list containing an empty list or a list with a single element.
say 1.permutations; # OUTPUT: «((1))»
method join§
method join( = '') is nodal
Converts the object to a list by calling self.list
, and calls .join
on the list. Can take a separator, which is an empty string by default.
(1..3).join.say; # OUTPUT: «123»<a b c>.join("❧").put; # OUTPUT: «a❧b❧c»
routine categorize§
multi method categorize()multi method categorize(Whatever)multi method categorize(, :!, :)multi method categorize(, :)multi categorize(, +items, :!, * )multi categorize(, +items, * )
The first form will always fail. The second form classifies on the identity of the given object, which usually only makes sense in combination with the :&as
argument.
In its simplest form, it uses a $test
whose result will be used as a key; the values of the key will be an array of the elements that produced that key as a result of the test.
say (1..13).categorize( * %% 3);say categorize( * %% 3, 1..13)# OUTPUT: «{False => [1 2 4 5 7 8 10 11 13], True => [3 6 9 12]}»
The :as
argument will normalize before categorizing
say categorize( * %% 3, -5..5, as => )# OUTPUT: «{False => [5 4 2 1 1 2 4 5], True => [3 0 3]}»
The $into
associative argument can be used to put the result instead of returning a new Hash
.
my ;my = (2002..2009).map( );.categorize( *.is-leap-year , into => );say# OUTPUT:# «{ False# => [2002-01-01 2003-01-01 2005-01-01 2006-01-01 2007-01-01 2009-01-01],# True => [2004-01-01 2008-01-01]}»
The function used to categorize can return an array indicating all possible bins their argument can be put into:
sub divisible-by( Int --> Array(Seq) )say (3..13).categorize( );# OUTPUT:# «{2 => [4 6 8 10 12], 3 => [3 6 9 12], 5 => [5 10], 7 => [7]}»
In this case, every number in the range is classified in as many bins as it can be divided by.
Support for using Whatever
as the test was added in Rakudo compiler version 2023.02.
routine classify§
multi method classify()multi method classify(Whatever)multi method classify(, :!, :)multi method classify(, :)multi classify(, +items, :!, * )multi classify(, +items, * )
The first form will always fail. The second form classifies on the identity of the given object, which usually only makes sense in combination with the :&as
argument.
The rest include a $test
argument, which is a function that will return a scalar for every input; these will be used as keys of a hash whose values will be arrays with the elements that output that key for the test function.
my = (2003..2008).map( );.classify( *.is-leap-year , into => my );say ;# OUTPUT: «{False => [2003-01-01 2005-01-01 2006-01-01 2007-01-01],# True => [2004-01-01 2008-01-01]}»
Similarly to .categorize
, elements can be normalized by the Callable
passed with the :as
argument, and it can use the :into
named argument to pass a Hash
the results will be classified into; in the example above, it's defined on the fly.
From version 6.d, .classify
will also work with Junction
s.
Support for using Whatever
as the test was added in Rakudo compiler version 2023.02.
routine reduce§
multi method reduce(Any: & --> Nil)multi method reduce(Any: )multi reduce (, +list)
This routine combines the elements in a list-y object, and produces a single result, by applying a binary subroutine. It applies its argument (or first argument for the sub form) as an operator to all the elements in the object (or second argument for the sub form), producing a single result. The subroutine must be either an infix operator or take two positional arguments. When using an infix operator, we must provide the code object of its subroutine version, i.e., the operator category, followed by a colon, then a list quote construct with the symbol(s) that make up the operator (e.g., infix:<+>
). See Operators.
say (1..4).reduce(:<+>); # OUTPUT: «10»say reduce :<+>, 1..4; # OUTPUT: «10»say reduce , 1..4; # OUTPUT: «1»sub hyphenate(Str \a, Str \b)say reduce , 'a'..'c'; # OUTPUT: «a-b-c»
Applied to a class, the routine will always return Nil
.
say Range.reduce(:<+>); # OUTPUT: «Nil»say Str.reduce(:<~>); # OUTPUT: «Nil»
See List.reduce for a more thorough discussion.
routine produce§
multi method produce(Any: & --> Nil)multi method produce(Any: )multi produce (, +list)
This is similar to reduce
, but returns a list with the accumulated values instead of a single result.
<10 5 3>.reduce( &[*] ).say ; # OUTPUT: «150»<10 5 3>.produce( &[*] ).say; # OUTPUT: «(10 50 150)»
The last element of the produced list would be the output produced by the .reduce
method.
If it's a class, it will simply return Nil.
method pairs§
multi method pairs(Any:)multi method pairs(Any:)
Returns an empty List
if the invocant is a type object:
say Num.pairs; # OUTPUT: «()»
For a value object, it converts the invocant to a List
via the list
method and returns the result of List.pairs on it.
<1 2 2 3 3 3>.Bag.pairs.say;# OUTPUT: «(1 => 1 3 => 3 2 => 2)»
In this case, every element (with weight) in a bag is converted to a pair.
method antipairs§
multi method antipairs(Any:)multi method antipairs(Any:)
Returns an empty List
if the invocant is a type object
Range.antipairs.say; # OUTPUT: «()»
If it's a value object, it returns the inverted list of pairs after converting it to a list of pairs; the values will become keys and the other way round.
%(s => 1, t=> 2, u => 3).antipairs.say ;# OUTPUT: «(2 => t 1 => s 3 => u)»
method invert§
multi method invert(Any:)multi method invert(Any:)
Applied to a type object will return an empty list; applied to an object will convert it to a list and apply List.invert
to it, that is, interchange key with value in every Pair. The resulting list needs to be a list of Pair
s.
"aaabbcccc".comb.Bag.invert.say; # OUTPUT: «(4 => c 3 => a 2 => b)»
In this case, a Bag
can be converted to a list of Pair
s. If the result of converting the object to a list is not a list of pairs, the method will fail.
routine kv§
multi method kv(Any:)multi method kv(Any:)multi kv()
Returns an empty List
if the invocant is a type object:
Sub.kv.say ;# OUTPUT: «()»
It calls list
on the invocant for value objects and returns the result of List.kv on it as a list where keys and values will be ordered and contiguous
<1 2 3>.kv.say; # OUTPUT: «(0 1 1 2 2 3)»
In the case of Positional
s, the indices will be considered keys.
method toggle§
method toggle(Any: * where .all ~~ Callable, Bool : --> Seq)
Iterates over the invocant, producing a Seq
, toggling whether the received values are propagated to the result on and off, depending on the results of calling Callables
in @conditions
:
say (1..15).toggle(* < 5, * > 10, * < 15); # OUTPUT: «(1 2 3 4 11 12 13 14)»say (1..15).toggle(:off, * > 2, * < 5, * > 10, * < 15); # OUTPUT: «(3 4 11 12 13 14)»
Imagine a switch that's either on or off (True
or False
), and values are produced if it's on. By default, the initial state of that switch is in "on" position, unless :$off
is set to a true value, in which case the initial state will be "off".
A Callable
from the head of @conditions
is taken (if any are available) and it becomes the current tester. Each value from the original sequence is tested by calling the tester Callable
with that value. The state of our imaginary switch is set to the return value from the tester: if it's truthy, set switch to "on", otherwise set it to "off".
Whenever the switch is toggled (i.e. switched from "off" to "on" or from "on" to "off"), the current tester Callable
is replaced by the next Callable
in @conditions
, if available, which will be used to test any further values. If no more tester Callable
s are available, the switch will remain in its current state until the end of iteration.
# our original sequence of elements:say list ^10; # OUTPUT: «(0 1 2 3 4 5 6 7 8 9)»# toggled result:say ^10 .toggle: * < 4, * %% 2, ; # OUTPUT: «(0 1 2 3 6 7)»# First tester Callable is `* < 4` and initial state of switch is "on".# As we iterate over our original sequence:# 0 => 0 < 4 === True switch is on, value gets into result, switch is# toggled, so we keep using the same Callable:# 1 => 1 < 4 === True same# 2 => 2 < 4 === True same# 3 => 3 < 4 === True same# 4 => 4 < 4 === False switch is now off, "4" does not make it into the# result. In addition, our switch got toggled, so# we're switching to the next tester Callable# 5 => 5 %% 2 === False switch is still off, keep trying to find a value# 6 => 6 %% 2 === True switch is now on, take "6" into result. The switch# toggled, so we'll use the next tester Callable# 7 => is-prime(7) === True switch is still on, take value and keep going# 8 => is-prime(8) === False switch is now off, "8" does not make it into# the result. The switch got toggled, but we# don't have any more tester Callables, so it# will remain off for the rest of the sequence.
Since the toggle of the switch's state loads the next tester Callable
, setting :$off
to a True
value affects when first tester is discarded:
# our original sequence of elements:say <0 1 2>; # OUTPUT: «(0 1 2)»# toggled result:say <0 1 2>.toggle: * > 1; # OUTPUT: «()»# First tester Callable is `* > 1` and initial state of switch is "on".# As we iterate over our original sequence:# 0 => 0 > 1 === False switch is off, "0" does not make it into result.# In addition, switch got toggled, so we change the# tester Callable, and since we don't have any more# of them, the switch will remain "off" until the end
The behavior changes when :off
is used:
# our original sequence of elements:say <0 1 2>; # OUTPUT: «(0 1 2)»# toggled result:say <0 1 2>.toggle: :off, * > 1; # OUTPUT: «(2)»# First tester Callable is `* > 1` and initial state of switch is "off".# As we iterate over our original sequence:# 0 => 0 > 1 === False switch is off, "0" does not make it into result.# The switch did NOT get toggled this time, so we# keep using our current tester Callable# 1 => 1 > 1 === False same# 2 => 2 > 1 === True switch is on, "2" makes it into the result
routine head§
multi method head(Any:) is rawmulti method head(Any: Callable )multi method head(Any: )
Returns either the first element in the object, or the first $n
if that's used.
"aaabbc".comb.head.put; # OUTPUT: «a»say ^10 .head(5); # OUTPUT: «(0 1 2 3 4)»say ^∞ .head(5); # OUTPUT: «(0 1 2 3 4)»say ^10 .head; # OUTPUT: «0»say ^∞ .head; # OUTPUT: «0»
In the first two cases, the results are different since there's no defined order in Mix
es. In the other cases, it returns a Seq
. A Callable
can be used to return all but the last elements:
say (^10).head( * - 3 );# OUTPUT: «(0 1 2 3 4 5 6)»
As of release 2022.07 of the Rakudo compiler, there is also a "sub" version of head
.
multi head(\specifier, +values)
It must have the head specifier as the first argument. The rest of the arguments are turned into a Seq
and then have the head
method called on it.
routine tail§
multi method tail() is rawmulti method tail()
Returns the last or the list of the $n
last elements of an object. $n
can be a Callable
, usually a WhateverCode
, which will be used to get all but the first n
elements of the object.
say (^12).reverse.tail ; # OUTPUT: «0»say (^12).reverse.tail(3); # OUTPUT: «(2 1 0)»say (^12).reverse.tail(*-7); # OUTPUT: «(4 3 2 1 0)»
As of release 2022.07 of the Rakudo compiler, there is also a "sub" version of tail
.
multi tail(\specifier, +values)
It must have the tail specifier as the first argument. The rest of the arguments are turned into a Seq
and then have the tail
method called on it.
method tree§
multi method tree(Any:)multi method tree(Any:)multi method tree(Any: Whatever )multi method tree(Any: Int(Cool) )multi method tree(Any: @ [, *])multi method tree(Any: , *)
Returns the class if it's undefined or if it's not Iterable
, returns the result of applying the tree
method to its invocant otherwise.
say Any.tree; # OUTPUT: «Any»
.tree
has different prototypes for Iterable
elements.
my = ( 'A', ('B','C', ('E','F','G')));say .tree(1).flat.elems; # OUTPUT: «6»say .tree(2).flat.elems; # OUTPUT: «2»say .tree( *.join("-"),*.join("—"),*.join("|"));# OUTPUT: «A-B—C—E|F|G»
With a number, it iteratively applies tree
to every element in the lower level; the first instance will apply .tree(0)
to every element in the array, and likewise for the next example.
The second prototype applies the WhateverCode
passed as arguments to every level in turn; the first argument will go to level 1 and so on. tree
can, thus, be a great way to process complex all levels of complex, multi-level, data structures.
method nl-out§
method nl-out(--> Str)
Returns Str
with the value of "\n". See IO::Handle.nl-out
for the details.
Num.nl-out.print; # OUTPUT: «»Whatever.nl-out.print;# OUTPUT: «»33.nl-out.print; # OUTPUT: «»
method combinations§
method combinations(|c)
Coerces the invocant to a list
by applying its .list
method and uses List.combinations
on it.
say (^3).combinations; # OUTPUT: «(() (0) (1) (2) (0 1) (0 2) (1 2) (0 1 2))»
Combinations on an empty data structure will return a list with a single element, an empty list; on a data structure with a single element it will return a list with two lists, one of them empty and the other with a single element.
say set().combinations; # OUTPUT: «(())»
method grep§
method grep(Mu , :, :, :, : --> Seq)
Coerces the invocant to a list
by applying its .list
method and uses List.grep
on it.
For undefined invocants, based on $matcher
the return value can be either ((Any))
or the empty List.
my ;say .grep(); # OUTPUT: «((Any))»say .grep(); # OUTPUT: «()»
method append§
multi method append(Any \SELF: |values)
In the case the instance is not a positional-thing, it instantiates it as a new Array
, otherwise clone the current instance. After that, it appends the values passed as arguments to the array obtained calling Array.append
on it.
my ;say .append; # OUTPUT: «[]»my ;say .append((1,2,3)); # OUTPUT: «[1 2 3]»
method values§
multi method values(Any:)multi method values(Any:)
Will return an empty list for undefined or class arguments, and the object converted to a list otherwise.
say (1..3).values; # OUTPUT: «(1 2 3)»say List.values; # OUTPUT: «()»
method collate§
method collate()
The collate
method sorts taking into account Unicode grapheme characteristics; that is, sorting more or less as one would expect instead of using the order in which their codepoints appear. collate
will behave this way if the object it is applied to is Iterable
.
say ('a', 'Z').sort; # (Z a)say ('a', 'Z').collate; # (a Z)say <ä a o ö>.collate; # (a ä o ö)my = 'aa' => 'value', 'Za' => 'second';say .collate; # (aa => value Za => second);
This method is affected by the $*COLLATION
variable, which configures the four collation levels. While Primary, Secondary and Tertiary mean different things for different scripts, for the Latin script used in English they mostly correspond with Primary being Alphabetic, Secondary being Diacritics and Tertiary being Case.
In the example below you can see how when we disable tertiary collation which in Latin script generally is for case, and also disable quaternary which breaks any ties by checking the codepoint values of the strings, we get Same back for A and a:
.set(:quaternary(False), :tertiary(False));say 'a' coll 'A'; # OUTPUT: «Same»say ('a','A').collate == ('A','a').collate; # OUTPUT: «True»
The variable affects the coll
operator as shown as well as this method.
method cache§
method cache()
Provides a List
representation of the object itself, calling the method list
on the instance.
method batch§
multi method batch(Int )multi method batch(Int :!)
Coerces the invocant to a list
by applying its .list
method and uses List.batch
on it.
method rotor§
multi method rotor(Any: Int , :)multi method rotor(Any: *, :)
Creates a Seq
that groups the elements of the object in lists of $batch
elements.
say (3..9).rotor(3); # OUTPUT: «((3 4 5) (6 7 8))»
With the :partial
named argument, it will also include lists that do not get to be the $batch
size:
say (3..10).rotor(3, :partial); # OUTPUT: «((3 4 5) (6 7 8) (9 10))»
.rotor
can be called with an array of integers and pairs, which will be applied in turn. While integers will establish the batch size, as above, Pair
s will use the key as batch size and the value as number of elements to skip if it's positive, or overlap if it's negative.
say (3..11).rotor(3, 2 => 1, 3 => -2, :partial);# OUTPUT: «((3 4 5) (6 7) (9 10 11) (10 11))»
In this case, the first batch (ruled by an integer) has 3 elements; the second one has 2 elements (key of the pair), but skips one (the number 8); the third one has size 2 (because partials are allowed), and an overlap of 2 also.
The overlap cannot be larger than the sublist size; in that case, it will throw an Exception
:
say (3..11).rotor(3, 2 => 1, 3 => -4, :partial);# OUTPUT: «(exit code 1) Rotorizing gap is out of range. Is: -4, should be in# -3..^Inf; Ensure a negative gap is not larger than the length of the# sublist »
Non-Int
values of $batch
will be coerced to Int:
say (3..9).rotor(3+⅓); # OUTPUT: «((3 4 5) (6 7 8))»
Please see also list.rotor
for examples applied to lists.
method sum§
method sum() is nodal
If the content is iterable, it returns the sum of the values after pulling them one by one, or 0 if the list is empty.
(3,2,1).sum; # OUTPUT: «6»say 3.sum; # OUTPUT: «3»
It will fail if any of the elements cannot be converted to a number.
multi method slice§
method slice(Any: * --> Seq)
Available as of the 2021.02 release of the Rakudo compiler.
Converts the invocant to a Seq
and then calls the slice method on it.
say (1..10).slice(0, 3..6, 8); # OUTPUT: «(1 4 5 6 7 9)»
routine snip§
multi snip(\matcher, +values)multi method snip(\values: \matcher)
Available as of 6.e language version (early implementation exists in Rakudo compiler 2022.07+).
The snip
method / subroutine provides a way to cut a given Iterable
into two or more List
s. A "snip" will be made as soon as the smartmatch of a value in the given Iterable
returns False. The matcher may also be a list of matchers: as soon as a "snip" was made, will it start checking using the next matcher. The rest of the Iterable
will be produced if there are no matchers left.
.say for snip * < 10, 2, 5, 13, 9, 6; # OUTPUT: «(2 5)(13 9 6)».say for snip (* < 10, * < 20), 5, 13, 29; # OUTPUT: «(5)(13)(29)».say for snip Int, 2, 5, 5, "a", "b"; # OUTPUT: «(2 5 5)(a b)».say for (2, 5, 13, 9, 6).snip(* < 10); # OUTPUT: «(2 5)(13 9 6)».say for (5, 13,29).snip(* < 10, * < 20); # OUTPUT: «(5)(13)(29)».say for (2, 5, 5, "a", "b").snip: Int; # OUTPUT: «(2 5 5)(a b)»
routine snitch§
multi snitch(\snitchee)multi snitch(, \snitchee)method snitch(\snitchee: = )
Available as of 6.e language version (early implementation exists in Rakudo compiler 2022.12+).
The snitch
method / subroutine is a debugging / logging tool that will always return any invocant / argument given unchanged.
By default, it will note the invocant / argument, but this can be overridden by specifying a Callable
that is expected to take the invocant / argument as its only argument.
(my = 42).snitch = 666; say ; # OUTPUT: «42666»(1..5).snitch; # OUTPUT: «1..5»(1..5).Seq.snitch; # OUTPUT: «(1 2 3 4 5)»(1..5).Seq.snitch(); # OUTPUT: «(1, 2, 3, 4, 5).Seq»(1..5).map(*+1).snitch; # OUTPUT: «(2 3 4 5 6)»say (1..3).Seq.snitch.map(*+2); # OUTPUT: «(1 2 3)(3 4 5)»
The same, using the feed operator:
(1..3).Seq ==> snitch() ==> map(*+2) ==> say(); # OUTPUT: «(1 2 3)(3 4 5)»
Using a custom logger:
my ;my = (1..3).Seq.snitch().map(*+2);say ; # OUTPUT: «[(1 2 3)]»say ; # OUTPUT: «[3 4 5]»