is Map
A Hash
is a mutable Map
; it implements Associative
through its inheritance of Map
and as such provides support for looking up values using keys, providing support for associative subscripting.
Hash
is the default type for variables with the %
sigil.
Hashes are mutable mappings from keys to values, known in other programming languages as dicts (Python), objects (Javascript) or Hash Maps (Java).
Basic usage:
# initialization with pairs:my = Spain => 'Madrid', 'United States' => 'Washington DC';# adding another pair:= 'Harare';# accessing a value by key:my = 'Spain';say "The capital of $country is %capitals";# getting all keys:say "I know the capitals of these countries: ", .keys.sort.join(', ');# check if a key is in a hash:if :exists# iterating over keys and values (unordered):for .kv -> ,
Although the order of the hashes is guaranteed to be random in every single call, still successive calls to .keys
and .values
are guaranteed to return them in the same order:
my = :1a, :2b; my = :5b, :6c;= .values;say .raku; # OUTPUT: «{:a(1), :b(5), :c(6)}»
In this case, b
will always be associated to 5 and c
to 6; even if two successive calls to keys
will return them in different order. Successive calls to any of them separately and repeatedly will always return the same order in any program invocation.
Please see the section on hash literals for different ways to declare a hash. Additionally, they can be declared using curly braces as long as these rules are followed:
Empty curly braces will always declare an empty hash.
A reference to $_ (even implicit) will instead declare a block.
A
Pair
or variable with%
as the first element will declare a hash.
given 3 ; # OUTPUT: «(Hash)»given 3 ; # OUTPUT: «(Block)»given 3 ;# OUTPUT: «(Block)»say .^name; # OUTPUT: «Block»
The next-to-last two cases are examples of the generation of Block
s in the presence of the topic variable $_
. The last case does not meet the third criterion for generating a hash, and thus generates a Block
.
A % in front of parentheses or square brackets will generate a Hash
as long as the elements can be paired.
say %( 'a', 3, :b(3), 'c', 3 ).^name; # OUTPUT: «Hash»
Elements in this hash can be paired both sides of the Pair :b(3)
.
say %(«a b c 1 2 3»).^name; # OUTPUT: «Hash»
An empty hash can be initialized either with empty curly braces or, since 6.d, %()
.
say %().^name; # OUTPUT: «Hash»say .^name; # OUTPUT: «Hash»
Hashes can be parameterized with types. You can change the type of the keys like this:
my = 2 => 3, 3 => 5, 5 => 7, 7 => 11, 11 => 13;
The type of the values defaults to Mu
, but you can constrain it to other types:
my Array ;
You can combine these two features:
my Array = 2 => [3, 5], 11 => [13, 17];
Methods§
method classify-list§
multi method classify-list(, *, : --> Hash)multi method classify-list(, *, : --> Hash)multi method classify-list(, *, : --> Hash)
Populates a Hash
by classifying the possibly-empty @list
of values using the given mapper
, optionally altering the values using the :&as
Callable
. The @list
cannot be lazy.
The mapper can be a Callable
that takes a single argument, an Associative
, or an Iterable
; this Callable
is guaranteed to be called only once per item. With Associative
and an Iterable
mappers, the values in the @list
represent the key and index of the mapper's value respectively. A Callable
mapper will be executed once per each item in the @list
, with that item as the argument and its return value will be used as the mapper's value.
Simple classification§
In simple classification mode, each mapper's value is any non-Iterable
and represents a key to classify @list
's item under:
say % .classify-list: , ^10;# OUTPUT: «{even => [0 2 4 6 8], odd => [1 3 5 7 9]}»my = <zero one two three four five>;my = foo => 'bar';say .classify-list: , 1, 2, 3, 4, 4;# OUTPUT: «{foo => bar, four => [4 4], one => [1], three => [3], two => [2]}»
The mapper's value is used as the key of the Hash
to which the @list
's item will be push
ed. See .categorize-list
if you wish to classify an item into multiple categories at once.
Multi-level classification§
In multi-level classification mode, each mapper's value is an Iterable
that represents a tree of hash keys to classify @list
's item under:
say % .classify-list:, ^10;# OUTPUT:# {# non-prime => {# even => [0 4 6 8],# odd => [1 9]# },# prime => {# even => [2],# odd => [3 5 7]# }# }
In the case we are using Iterable
s and not Callable
s, each of those Iterable
s must have the same number of elements, or the method will throw an exception. This restriction exists to avoid conflicts when the same key is a leaf of one value's classification but a node of another value's classification.
my = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']];say % .classify-list: , 1,2,1,1,2,0;# OUTPUT: «{1a => {1b => {1c => [0]}}, 2a => {2b => {2c => [1 1 1]}}, 3a => {3b => {3c => [2 2]}}}»
Every element of the array represents a different level in the tree, with the elements of the list that is being mapped used as index, and the elements of the mapper array used as keys to the different levels. So 0
selects the first sub-array and then the subsequent levels are built by running over the rest of the elements of that sub-array.
my = [['1a','1b'],['2a','2b'],['3a','3b']];say % .classify-list: , 1,0,1,1,1,0,2;# OUTPUT: «{1a => {1b => [0 0]}, 2a => {2b => [1 1 1 1]}, 3a => {3b => [2]}}»
From version 6.d, trying to use Iterable
s of different size will throw an error:
my = [<1a 1b>, <2a 2b 2fail>];say % .classify-list: , 1,0,1,1,1,0;# OUTPUT: «mapper on classify-list computed to an item with different number# of elements in it than previous items, which cannot be used because all# values need to have the same number of elements. Mixed-level classification# is not supported. in block <unit>…»
:&as
value modifier§
If :&as
Callable
argument is specified, it will be called once per each item of @list
, with the value as the argument, and its return value will be used instead of the original @list
's item:
say % .classify-list: :as, , ^5;# OUTPUT (slightly altered manually, for clarity):# {# even => ['Value is 0', 'Value is 2', 'Value is 4'],# odd => ['Value is 1', 'Value is 3']# }
method categorize-list§
multi method categorize-list(, *, : --> Hash)multi method categorize-list(, *, : --> Hash)multi method categorize-list(, *, : --> Hash)
Populates a Hash
by classifying the possibly-empty @list
of values using the given mapper
, optionally altering the values using the :&as
Callable
. The @list
cannot be lazy.
The mapper can be a Callable
that takes a single argument, an Associative
, or an Iterable
. With Associative
and an Iterable
mappers, the values in the @list
represent the key and index of the mapper's value respectively. A Callable
mapper will be executed once per each item in the @list
, with that item as the argument and its return value will be used as the mapper's value.
Simple categorization§
The mapper's value is expected to be a possibly empty list of non-Iterable
s that represent categories to place the value into:
say % .categorize-list:, ^10;# OUTPUT:# {# prime => [2 3 5 7]# even => [0 2 4 6 8],# odd => [1 3 5 7 9],# largish => [6 7 8 9],# }
Notice how some items, e.g. 6
and 7
, are present in several categories.
Multi-level categorization§
In multi-level categorization, the categories produced by the mapper are Iterables and categorization combines features of classify, by producing nested hashes of classifications for each category.
say % .categorize-list:, ^10;# OUTPUT:# {# largish => {# non-prime => [6 8 9],# prime => [7]# },# smallish => {# non-prime => [0 1 4],# prime => [2 3 5]# }# }
The mapper in the snippet above produces a single-item list (note the significant trailing comma) with a two-item Array
in it. The first item in that array indicates the first level of classification: the largish
/smallish
categories the routine produces. The second item in that array indicates further levels of classification, in our case the classification into prime
/non-prime
inside of each category.
NOTE:: every Iterable
s category must have the same number of elements, or the method will throw an exception. This restriction exists to avoid conflicts when the same key is a leaf of one value's classification but a node of another value's classification.
:&as
value modifier§
If :&as
Callable
argument is specified, it will be called once per each item of @list
, with the value as the argument, and its return value will be used instead of the original @list
's item:
say % .categorize-list: :as, , ^5;# OUTPUT (slightly altered manually, for clarity):# {# even => ['Value is 0', 'Value is 2', 'Value is 4'],# odd => ['Value is 1', 'Value is 3']# }
method push§
method push(Hash: +new)
Adds the new
elements to the hash with the same semantics as hash assignment, but with three exceptions:
The hash isn't emptied first, i.e. old pairs are not deleted.
If a key already exists in the hash, and the corresponding value is an
Array
, the new value is pushed onto the array (instead of replacing it).If a key already exists in the hash, and the corresponding value is not an
Array
, old and new value are both placed into an array in the place of the old value.
Example:
my = a => 1;.push: (a => 1); # a => [1,1].push: (a => 1) xx 3 ; # a => [1,1,1,1,1].push: (b => 3); # a => [1,1,1,1,1], b => 3.push('c' => 4); # a => [1,1,1,1,1], b => 3, c => 4push , 'd' => 5; # a => [1,1,1,1,1], b => 3, c => 4, d => 5
Please note that literal pairs in the argument list may be interpreted as named arguments and as such won't end up in the Hash
:
my .= push(e => 6);say .raku; # OUTPUT: «{}»
Use the corresponding subroutine to catch this kind of mistake:
push my , f => 7;CATCH ;# OUTPUT: «Unexpected named argument 'f' passed»
Also note that push can be used as a replacement for assignment during hash initialization very useful ways. Take for instance the case of an inverted index:
my = 'hash' => 323, 'pair' => 322, 'pipe' => 323;(my ).push: .invert;say ; # OUTPUT: «{322 => pair, 323 => [pipe hash]}»
Note that such an initialization could also be written as
my = 'hash' => 323, 'pair' => 322, 'pipe' => 323;my .= push: .invert;
Note: Compared to append
, push
will add the given value as is, whereas append
will slip
it in:
my = :a[42, ]; .push: "a" => <a b c a>;say ; # OUTPUT: «{a => [42 (a b c a)]}»my = :a[42, ]; .append: "a" => <a b c a>;say ; # OUTPUT: «{a => [42 a b c a]}»
method append§
method append(+)
Append the provided Pairs or even sized list to the Hash. If a key already exists, turn the existing value into an Array
and push new value onto that Array
. Please note that you can't mix even sized lists and lists of Pairs. Also, bare Pair
s or colon pairs will be treated as named arguments to .append
.
my = a => 1;.append('b', 2, 'c', 3);.append( %(d => 4) );say ;# OUTPUT: «{a => 1, b => 2, c => 3, d => 4}».append('a', 2);# OUTPUT: «{a => [1 2], b => 2, c => 3, d => 4}»
Note: Compared to push
, append
will slip
in the given value, whereas push
will add it as is:
my = :a[42, ]; .append: "a" => <a b c a>;say ; # OUTPUT: «{a => [42 a b c a]}»my = :a[42, ]; .push: "a" => <a b c a>;say ; # OUTPUT: «{a => [42 (a b c a)]}»
method default§
method default(Hash:)
Returns the default value of the invocant, i.e. the value which is returned when a non existing key is used to access an element in the Hash
. Unless the Hash
is declared as having a default value by using the is default trait the method returns the type object (Any)
.
my = 'apples' => 3, 'oranges' => 7;say .default; # OUTPUT: «(Any)»say ; # OUTPUT: «(Any)»my is default(1) = 'apples' => 3, 'oranges' => 7;say .default; # OUTPUT: «1»say + ; # OUTPUT: «4»
method keyof§
method keyof()
Returns the type constraint for the keys of the invocant. For normal hashes the method returns the coercion type (Str(Any))
while for non-string keys hashes the type used in the declaration of the Hash
is returned.
my = 'apples' => 3, 'oranges' => 7; # (no key type specified)say .keyof; # OUTPUT: «(Str(Any))»my = 'oranges' => 7; # (keys must be of type Str)say .keyof; # OUTPUT: «(Str)»= 'apples'; # throws exceptionCATCH ;# OUTPUT: «X::TypeCheck::Binding: Type check failed in binding to key; expected Str but got Int (3)»my ; # (this time, keys must be of type Int)= 4096;say .keyof; # OUTPUT: «(Int)»
method of§
method of(Hash:)
Returns the type constraint for the values of the invocant. By default, i.e., if no type constraint is given during declaration, the method returns (Mu)
.
my = 'apples' => 3, 'oranges' => 7; # (no type constraint specified)say .of; # OUTPUT: «(Mu)»my Int = 'oranges' => 7; # (values must be of type Int)say .of; # OUTPUT: «(Int)»
routine dynamic§
method dynamic(--> Bool)
Returns True
if the invocant has been declared with the is dynamic trait.
my ;say .dynamic; # OUTPUT: «False»my is dynamic;say .dynamic; # OUTPUT: «True»
If you declare a variable with the *
twigil is dynamic
is implied.
my ;say .dynamic; # OUTPUT: «True»
Note that in the Scalar
case you have to use the VAR
method in order to get correct information.
my is dynamic = %('apples' => 5);say .dynamic; # OUTPUT: «False» (wrong, don't do this)say .VAR.dynamic; # OUTPUT: «True» (correct approach)
Subscript Adverbs§
Some methods are implemented as adverbs on subscripts (consult the operators documentation for more information).
:exists
§
The adverb :exists
returns Bool::True
if a key exists in the Hash. If more than one key is supplied it returns a List
of Bool
.
my = a => 1, b => 2;say <a>:exists; # OUTPUT: «True»say <a b>:exists; # OUTPUT: «(True True)»
:delete
§
Use :delete
to remove a Pair
from the Hash
. In addition, the value is always returned but the removal only happens if delete is true.
my = a => 1;say ; # OUTPUT: «{a => 1}»say .elems; # OUTPUT: «1»<a>:delete;say ; # OUTPUT: «{}»say .elems; # OUTPUT: «0»
:p
§
The adverb :p
returns a Pair
or a List of Pair
instead of just the value.
my = a => 1, b => 2;say <a>:p; # OUTPUT: «a => 1»say <a b>:p; # OUTPUT: «(a => 1 b=> 2)»
:v
and :k
§
The adverbs :v
and :k
return the key or value or a list thereof.
my = a => 1, b => 2;say <a>:k; # OUTPUT: «a»say <a b>:k; # OUTPUT: «(a b)»
The adverb :kv
returns a list of keys and values.
my = a => 1, b => 2, c => 3;say <a c>:kv; # OUTPUT: «(a 1 c 3)»
You can also use the adverbs without knowing anything about the hash by using empty angle brackets in which case all the keys and values will be listed:
my = a => 1;my = a => 1, b => 2;say <>:k; # OUTPUT: «(a)»say <>:v; # OUTPUT: «(1)»say <>:k; # OUTPUT: «(a b)»say <>:v; # OUTPUT: «(1 2)»