Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why adding a type before a hash variable that build with fat arrow syntax leaded to type check failed error?

Raku is gradual typing language. So the code below:

my %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

is the same as:

my Hash %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

However, it reports an error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type check failed in assignment to %hash; expected Hash but got Rat (4.5)

Why adding a type before a hash variable that build with fat arrow syntax leaded to type check failed error?

>Solution :

When you say my Hash %hash, you’re specifying a Hash that will only take Hash as a value. And in your example, you’re putting Rats into the hash as values, not Hashes. Which is what the error message is trying to tell you.

Your example would make more sense this way:

my Numeric %hash = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

in which you force all values to be Numeric.

Another way of writing that, is:

my %hash is Hash[Numeric] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

The first way is just syntactic sugar for the second.

If you also want to limit the keys, there are also two ways to do that:

my %hash is Hash[Numeric,Str] = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

would limit the keys to Str. Note that by default, the type is Str(), aka: coerce anything to Str, which is not the same.

The more syntactic sugary way is:

my Numeric %hash{Str} = abc => 4.5, abd => 5.5, bcd => 6.4, bce => 3.6;

which I think, is more readable as it is clear what the typing of the keys is.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading