class Pair
Key/value pair
does Associative
Consists of two parts, a key and a value. Pair
s can be seen as the atomic units in Hash
es, and they are also used in conjunction with named arguments and parameters.
There are many syntaxes for creating Pair
s:
Pair.new('key', 'value'); # The canonical way'key' => 'value'; # this...:key<value>; # ...means the same as this:key<value1 value2>; # But this is key => <value1 value2>:foo(127); # short for foo => 127:127foo; # the same foo => 127
Note that last form supports Non-ASCII numerics as well:
# use MATHEMATICAL DOUBLE-STRUCK DIGIT THREEsay (:𝟛math-three); # OUTPUT: «math-three => 3»
You can also use an identifier-like literal as key; this will not need the quotes as long as it follows the syntax of ordinary identifiers:
(foo => 127) # the same foo => 127
Variants of this are
:key; # same as key => True:!key; # same as key => False
And this other variant, to be used in routine invocation
sub colon-pair( : )my = 'value';colon-pair( : ); # OUTPUT: «value»colon-pair( key-value => ); # OUTPUT: «value»
Colon pairs can be chained without a comma to create a List of Pairs. Depending on context you may have to be explicit when assigning colon lists.
sub s(*);s :a1:b2;# OUTPUT: «{:a1, :b2}»my $manna = :a1:b2:c3;say .^name;# OUTPUT: «Pair»= (:a1:b2:c3);say .^name;# OUTPUT: «List»
Any variable can be turned into a Pair
of its name and its value.
my = 10;my = :;say ; # OUTPUT: «bar => 10»
It is worth noting that when assigning a Scalar as value of a Pair
the value holds the container of the value itself. This means that it is possible to change the value from outside of the Pair
itself:
my = 'value A';my = a => ;.say; # OUTPUT: «a => value A»= 'value B';.say; # OUTPUT: «a => value B»
Please also note that this behavior is totally unrelated to the way used to build the Pair
itself (i.e., explicit usage of new
, use of colon, fat arrow), as well as if the Pair
is bound to a variable.
It is possible to change the above behavior forcing the Pair
to remove the scalar container and to hold the effective value itself via the method freeze:
my = 'value B';my = a => ;.freeze;= 'value C';.say; # OUTPUT: «a => value B»
As Pair implements Associative role, its value can be accessed using Associative subscription operator, however, due to Pair's singular nature, the pair's value will be only returned for the pair's key. Nil object will be returned for any other key. Subscript adverbs such as :exists can be used on Pair.
my = a => 5;say <a>; # OUTPUT: «5»say <a>:exists; # OUTPUT: «True»say <no-such-key>; # OUTPUT: «Nil»
Methods
method new
Defined as:
multi method new(Pair: Mu , Mu )multi method new(Pair: Mu :, Mu :)
Constructs a new Pair object.
method ACCEPTS
Defined as:
multi method ACCEPTS(Pair $: )multi method ACCEPTS(Pair $: Pair )multi method ACCEPTS(Pair $: Mu )
If %topic
is an Associative, looks up the value using invocant's key in it and checks invocant's value .ACCEPTS
that value:
say %(:42a) ~~ :42a; # OUTPUT: «True»say %(:42a) ~~ :10a; # OUTPUT: «False»
If $topic
is another Pair, checks the invocant's value .ACCEPTS
the $topic
's value. Note that the keys are not considered and can be different:
say :42a ~~ :42a; # OUTPUT: «True»say :42z ~~ :42a; # OUTPUT: «True»say :10z ~~ :42a; # OUTPUT: «False»
If $topic
is any other value, the invocant Pair
's key is treated as a method name. This method is called on $topic
, the boolean result of which is compared against the invocant Pair
's boolean value. For example, primality can be tested using smartmatch:
say 3 ~~ :is-prime; # OUTPUT: «True»say 3 ~~ is-prime => 'truthy'; # OUTPUT: «True»say 4 ~~ :is-prime; # OUTPUT: «False»
This form can also be used to check Bool values of multiple methods on the same object, such as IO::Path, by using Junctions:
say "foo" .IO ~~ :f & :rw; # OUTPUT: «False»say "/tmp".IO ~~ :!f; # OUTPUT: «True»say "." .IO ~~ :f | :d; # OUTPUT: «True»
method antipair
Defined as:
method antipair(--> Pair)
Returns a new Pair
object with key and value exchanged.
my = (6 => 'Perl').antipair;say .key; # OUTPUT: «Perl»say .value; # OUTPUT: «6»
method key
Defined as:
multi method key(Pair:)
Returns the key part of the Pair
.
my = (Perl => 6);say .key; # OUTPUT: «Perl»
method value
Defined as:
multi method value(Pair:) is rw
Returns the value part of the Pair
.
my = (Perl => 6);say .value; # OUTPUT: «6»
infix cmp
Defined as:
multi sub infix:<cmp>(Pair, Pair)
The type-agnostic comparator; compares two Pair
s. Compares first their key parts, and then compares the value parts if the keys are equal.
my = (Apple => 1);my = (Apple => 2);say cmp ; # OUTPUT: «Less»
method fmt
Defined as:
multi method fmt(Pair: Str --> Str)
Takes a format string, and returns a string the key and value parts of the Pair
formatted. Here's an example:
my = :Earth(1);say .fmt("%s is %.3f AU away from the sun")# OUTPUT: «Earth is 1.000 AU away from the sun»
For more about format strings, see sprintf.
method kv
Defined as:
multi method kv(Pair: --> List)
Returns a two-element List
with the key and value parts of Pair
, in that order. This method is a special case of the same-named method on Hash
, which returns all its entries as a list of keys and values.
my = (Perl => 6);say .kv[0]; # OUTPUT: «Perl»say .kv[1]; # OUTPUT: «6»
method pairs
Defined as:
multi method pairs(Pair:)
Returns a list of one Pair
, namely this one.
my = (Perl => 6);say .pairs.^name; # OUTPUT: «List»say .pairs[0]; # OUTPUT: «Perl => 6»
method antipairs
Defined as:
multi method antipairs(Pair:)
Returns a List containing the antipair of the invocant.
my = (6 => 'Perl').antipairs;say .^name; # OUTPUT: «List»say .first; # OUTPUT: «Perl => 6»say .first.^name; # OUTPUT: «Pair»
method invert
Defined as:
method invert(Pair: --> Seq)
Returns a Seq. If the .value
of the invocant is NOT an Iterable, the Seq will contain a single Pair whose .key
is the .value
of the invocant and whose .value
is the .key
of the invocant:
:foo<bar>.invert.perl.say; # OUTPUT: «(:bar("foo"),).Seq»
If invocant's .value
is an Iterable, the returned Seq will contain the same number of Pairs as items in the .value
, with each of those items a .key
of a pair and the .key
of the invocant the .value
of that pair:
:foo<Perl is great>.invert.perl.say;# OUTPUT: «(:Perl("foo"), :is("foo"), :great("foo")).Seq»:foo.invert.perl.say;# OUTPUT: «((:a(42)) => "foo", (:b(72)) => "foo").Seq»
To perform the exact .key
and .value
swap, use .antipair
method.
method keys
Defined as:
multi method keys(Pair: --> List)
Returns a List containing the key of the invocant.
say ('Perl' => 6).keys; # OUTPUT: «(Perl)»
method values
Defined as:
multi method values(Pair: --> List)
Returns a List containing the value of the invocant.
say ('Perl' => 6).values; # OUTPUT: «(6)»
method freeze
Defined as:
method freeze(Pair:)
Makes the value of the Pair
read-only, by removing it from its Scalar container, and returns it.
my = "apple";my = Pair.new('key', );.value = "orange"; # this works as expected.say; # OUTPUT: «key => orange».freeze.say; # OUTPUT: «orange».value = "a new apple"; # FailsCATCH ;# OUTPUT: «X::Assignment::RO: Cannot modify an immutable Str (apple)»
NOTE: this method is deprecated as of 6.d language version. Instead, create a new Pair
, with a decontainerized key/value.
.=Map.=head.say; # OUTPUT: «orange»
method Str
Defined as:
multi method Str(Pair: --> Str)
Returns a string representation of the invocant formatted as key ~ \t ~ value.
my = eggs => 3;say .Str; # OUTPUT: «eggs 3»
method Pair
Defined as:
method Pair()
Returns the invocant Pair object.
my = eggs => 3;say .Pair === ; # OUTPUT: «True»
Type Graph
Routines supplied by role Associative
Pair does role Associative, which provides the following routines:
(Associative) method of
Defined as:
method of()
Associative
is actually a parameterized role which can use different classes for keys and values. As seen at the top of the document, by default it coerces to Str
for the key and uses a very generic Mu
for value.
my ;say .of;# OUTPUT: «(Mu)»
The value is the first parameter you use when instantiating Associative
with particular classes:
is Hash does Associative[Cool,DateTime] ;my := DateHash.new;say .of; # OUTPUT: «(Cool)»
(Associative) method keyof
Defined as:
method keyof()
Returns the parameterized key used for the Associative role, which is Any
coerced to Str
by default. This is the class used as second parameter when you use the parameterized version of Associative.
my ;.keyof; #OUTPUT: «(Str(Any))»
(Associative) method AT-KEY
method AT-KEY(\key)
Should return the value / container at the given key.
(Associative) method EXISTS-KEY
method EXISTS-KEY(\key)
Should return a Bool
indicating whether the given key actually has a value.
(Associative) method STORE
method STORE(\values, :)
This method should only be supplied if you want to support the:
my is Foo = a => 42, b => 666;
syntax for binding your implementation of the Associative
role.
Should accept the values to (re-)initialize the object with, which either could consist of Pair
s, or separate key/value pairs. The optional named parameter will contain a True
value when the method is called on the object for the first time. Should return the invocant.