🦋 74. Typed hashes in Perl 6

In Perl 6, you can restrict the content of a variable container by specifying its type, for example:

my Int $i;

There is only one value in a scalar variable. You can extend the concept to arrays and let its element to keep only integers, as it is done in the next example:

> my Int @i;
[]

> @i.push(42);
[42]

> @i.push('Hello');
Type check failed in assignment to @i;
expected Int but got Str ("Hello")
  in block <unit> at <unknown file> line 1

Hashes keeps pairs, so you can specify the type of both keys and values. The syntax is not deductible from the above examples.

First, let us announce the type of the value:

my Str %s;

Now, it is possible to have strings as values:

> %s<Hello> = 'World'
World

> %s<42> = 'Fourty-two'
Fourty-two

But it’s not possible to save integers:

> %s<x> = 100
Type check failed in assignment to %s;
expected Str but got Int (100)
  in block <unit> at <unknown file> line 1

(By the way, notice that in the case of %s<42> the key is a string.)

To specify the type of the second dimension, namely, of the hash keys, give the type in curly braces:

my %r{Rat};

This variable is also referred to as object hash.

Having this, Perl expects you to have Rat keys for this variable:

> %r<22/7> = pi
3.14159265358979

> %r
{22/7 => 3.14159265358979}

Attempts to use integers or strings, for example, fail:

> %r<Hello> = 1
Type check failed in binding to parameter 'key';
expected Rat but got Str ("Hello")
  in block <unit> at <unknown file> line 1

> %r{23} = 32
Type check failed in binding to parameter 'key';
expected Rat but got Int (23)
  in block <unit> at <unknown file> line 1

Finally, you can specify the types of both keys and values:

my Str %m{Int};

This variable can be used for translating month number to month names but not vice versa:

> %m{3} = 'March'
March

> %m<March> = 3
Type check failed in binding to parameter 'key';
expected Int but got Str ("March")
  in block <unit> at <unknown file> line 1

 

One thought on “🦋 74. Typed hashes in Perl 6

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s