class Hash

Mapping from strings to itemized values
class Hash 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 %capitals = Spain => 'Madrid', 'United States' => 'Washington DC';
# adding another pair:
    %capitals{'Zimbabwe'} = 'Harare';
# accessing a value by key:
    my $country = 'Spain';
    say "The capital of $country is %capitals{$country}";
# getting all keys:
    say "I know the capitals of these countries: ", %capitals.keys.sort.join(', ');
# check if a key is in a hash:
    if %capitals{'Europe'}:exists {
        # not executed
    }
# iterating over keys and values (unordered):
    for %capitals.kv -> $country, $capital {
        say "$capital is the capital of $country";
    }

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 %orig = :1a, :2b; my %new = :5b, :6c;
    %orig{ %new.keys } = %new.values;
    say %orig.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 { say WHAT {3 => 4, :b}  };     # OUTPUT: «(Hash)␤»
given 3 { say WHAT {3 => 4, :b($_)} };  # OUTPUT: «(Block)␤»
given 3 { say WHAT {3 => 4, :b(.Num)} };# OUTPUT: «(Block)␤»
say { 'a',:b(3), 'c' }.^name;           # OUTPUT: «Block␤»

The next-to-last two cases are examples of the generation of Blocks 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 %next-prime{Int} = 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 %lists;

You can combine these two features:

my Array %next-primes{Int} = 2 => [3, 5], 11 => [13, 17];

Methods

method classify-list

multi method classify-list(&mapper, *@list, :&as --> Hash:D)
    multi method classify-list(%mapper, *@list, :&as --> Hash:D)
    multi method classify-list(@mapper, *@list, :&as --> Hash:D)

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: { $_ %% 2 ?? 'even' !! 'odd' }, ^10;
# OUTPUT: «{even => [0 2 4 6 8], odd => [1 3 5 7 9]}␤»

my @mapper = <zero one two three four five>;
my %hash = foo => 'bar';
say %hash.classify-list: @mapper, 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 pushed. 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: {
        [
            (.is-prime ?? 'prime' !! 'non-prime'),
            ($_ %% 2   ?? 'even'  !! 'odd'      ),
        ]
    }, ^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 Iterables and not Callables, each of those Iterables 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 @mapper = [['1a','1b','1c'],['2a','2b','2c'],['3a','3b','3c']];
say % .classify-list: @mapper, 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 @mapper = [['1a','1b'],['2a','2b'],['3a','3b']];
say % .classify-list: @mapper, 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 Iterables of different size will throw an error:

my @mapper = [<1a 1b>, <2a 2b 2fail>];
say % .classify-list: @mapper, 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{"Value is $_"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^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(&mapper, *@list, :&as --> Hash:D)
    multi method categorize-list(%mapper, *@list, :&as --> Hash:D)
    multi method categorize-list(@mapper, *@list, :&as --> Hash:D)

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-Iterables that represent categories to place the value into:

say % .categorize-list: {
        gather {
            take 'prime'   if .is-prime;
            take 'largish' if $_ > 5;
            take $_ %% 2 ?? 'even' !! 'odd';
        }
    }, ^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: {
        [
            $_ > 5    ?? 'largish' !! 'smallish',
            .is-prime ?? 'prime'   !! 'non-prime',
        ],
    }, ^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 Iterables 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{"Value is $_"}, { $_ %% 2 ?? 'even' !! 'odd' }, ^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:D: +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 %h  = a => 1;
    %h.push: (a => 1);              # a => [1,1]
    %h.push: (a => 1) xx 3 ;        # a => [1,1,1,1,1]
    %h.push: (b => 3);              # a => [1,1,1,1,1], b => 3
    %h.push('c' => 4);              # a => [1,1,1,1,1], b => 3, c => 4
    push %h, '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 %h .= push(e => 6);
    say %h.raku; # OUTPUT: «{}␤»

Use the corresponding subroutine to catch this kind of mistake:

push my %h, f => 7;
    CATCH { default { put .message } };
    # 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 %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
    (my %inv).push: %wc.invert;
    say %inv;                     # OUTPUT: «{322 => pair, 323 => [pipe hash]}␤»

Note that such an initialization could also be written as

my %wc = 'hash' => 323, 'pair' => 322, 'pipe' => 323;
    my %inv .= push: %wc.invert;

Note: Compared to append, push will add the given value as is, whereas append will slip it in:

my %ha = :a[42, ]; %ha.push: "a" => <a b c a>;
    say %ha; # OUTPUT: «{a => [42 (a b c a)]}␤»
my %hb = :a[42, ]; %hb.append: "a" => <a b c a>;
    say %hb; # OUTPUT: «{a => [42 a b c a]}␤»

method append

method append(+@values)

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 Pairs or colon pairs will be treated as named arguments to .append.

my %h = a => 1;
    %h.append('b', 2, 'c', 3);
    %h.append( %(d => 4) );
    say %h;
    # OUTPUT: «{a => 1, b => 2, c => 3, d => 4}␤»
    %h.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 %hb = :a[42, ]; %hb.append: "a" => <a b c a>;
    say %hb; # OUTPUT: «{a => [42 a b c a]}␤»
my %ha = :a[42, ]; %ha.push: "a" => <a b c a>;
    say %ha; # OUTPUT: «{a => [42 (a b c a)]}␤»

method default

method default(Hash:D:)

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 %h1 = 'apples' => 3, 'oranges' => 7;
    say %h1.default;                                       # OUTPUT: «(Any)␤»
    say %h1{'bananas'};                                    # OUTPUT: «(Any)␤»
my %h2 is default(1) = 'apples' => 3, 'oranges' => 7;
    say %h2.default;                                       # OUTPUT: «1␤»
    say %h2{'apples'} + %h2{'bananas'};                    # 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 %h1 = 'apples' => 3, 'oranges' => 7;  # (no key type specified)
    say %h1.keyof;                           # OUTPUT: «(Str(Any))␤»
my %h2{Str} = 'oranges' => 7;            # (keys must be of type Str)
    say %h2.keyof;                           # OUTPUT: «(Str)␤»
    %h2{3} = 'apples';                       # throws exception
    CATCH { default { put .^name, ': ', .Str } };
    # OUTPUT: «X::TypeCheck::Binding: Type check failed in binding to key; expected Str but got Int (3)␤»
my %h3{Int};                             # (this time, keys must be of type Int)
    %h3{42} = 4096;
    say %h3.keyof;                           # OUTPUT: «(Int)␤»

method of

method of(Hash:D:)

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 %h1 = 'apples' => 3, 'oranges' => 7;  # (no type constraint specified)
    say %h1.of;                              # OUTPUT: «(Mu)␤»
my Int %h2 = 'oranges' => 7;             # (values must be of type Int)
    say %h2.of;                              # OUTPUT: «(Int)␤»

routine dynamic

method dynamic(--> Bool:D)

Returns True if the invocant has been declared with the is dynamic trait.

my %a;
    say %a.dynamic;                          # OUTPUT: «False␤»
my %b is dynamic;
    say %b.dynamic;                          # OUTPUT: «True␤»

If you declare a variable with the * twigil is dynamic is implied.

my %*b;
    say %*b.dynamic;                         # OUTPUT: «True␤»

Note that in the Scalar case you have to use the VAR method in order to get correct information.

my $s is dynamic = %('apples' => 5);
    say $s.dynamic;                   # OUTPUT: «False␤»  (wrong, don't do this)
    say $s.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 %h = a => 1, b => 2;
    say %h<a>:exists;   # OUTPUT: «True␤»
    say %h<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 %h = a => 1;
    say %h;         # OUTPUT: «{a => 1}␤»
    say %h.elems;   # OUTPUT: «1␤»
%h<a>:delete;
    say %h;         # OUTPUT: «{}␤»
    say %h.elems;   # OUTPUT: «0␤»

:p

The adverb :p returns a Pair or a List of Pair instead of just the value.

my %h = a => 1, b => 2;
    say %h<a>:p;    # OUTPUT: «a => 1␤»
    say %h<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 %h = a => 1, b => 2;
    say %h<a>:k;    # OUTPUT: «a␤»
    say %h<a b>:k;  # OUTPUT: «(a b)␤»

The adverb :kv returns a list of keys and values.

my %h = a => 1, b => 2, c => 3;
    say %h<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 %h1 = a => 1;
    my %h2 = a => 1, b => 2;
    say %h1<>:k; # OUTPUT: «(a)␤»
    say %h1<>:v; # OUTPUT: «(1)␤»
    say %h2<>:k; # OUTPUT: «(a b)␤»
    say %h2<>:v; # OUTPUT: «(1 2)␤»

See Also

class Array

Sequence of itemized values

class Bag

Immutable collection of distinct objects with integer weights

class BagHash

Mutable collection of distinct objects with integer weights

class Capture

Argument list suitable for passing to a Signature

class IterationBuffer

Low level storage of positional values

class List

Sequence of values

class Map

Immutable mapping from strings to values

class Mix

Immutable collection of distinct objects with Real weights

class MixHash

Mutable collection of distinct objects with Real weights

class NFC

Codepoint string in Normal Form C (composed)

class NFD

Codepoint string in Normal Form D (decomposed)

class NFKC

Codepoint string in Normal Form KC (compatibility composed)

class NFKD

Codepoint string in Normal Form KD (compatibility decomposed)

class Pair

Key/value pair

class PseudoStash

Stash type for pseudo-packages

class Range

Interval of ordered values

class Seq

An iterable, potentially lazy sequence of values

class Set

Immutable collection of distinct objects

class SetHash

Mutable collection of distinct objects

class Slip

A kind of List that automatically flattens into an outer container

class Stash

Table for "our"-scoped symbols

class Uni

A string of Unicode codepoints

class utf8

Mutable uint8 buffer for utf8 binary data

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