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:
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.