On Sat, 01 Feb 2020, Paul Procacci wrote:
> Hey ladies/gents,
> 
> How would one go about defining a subset of a Hash who's key's and values
> are both constrained by something ....
> 
> I've read https://docs.perl6.org/type/Hash and it does make mention of
> constraining keys and values, but not within the context of a subset.
> Before I go ripping my hair out, I want to make sure I'm doing things right.
> 
> For instance, what if I want to define a subset that uses a Hash as it's
> base class, in which I want to add the constraint that it's keys must be
> strings yet it's values are constrained to only accept Int's?
> 

You would make a subset of Hash if you are getting Hashes and you want
to give some common code that checks the validity of the Hash a name.
If you want a new type that you can actually create objects from, the
solution is subclassing, not subsetting, but works similarly to below.
(Just to make sure you're not surprised when you can't call .new on
your subset later.)

With a subset you could do:

    subset PhoneBook of Hash[Int, Str];

    my Int %pb{Str};
    %pb<tobias>   = +49_123_4567_6789;  # good
    try %pb<paul> = "unknown";          # fails

    dd %pb  #= Hash[Int,Str] %pb = (my Int %{Str} = :tobias(4912345676789))
    say %pb ~~ PhoneBook  #= True

to the same effect.

Note that if you subset PhoneBook of Hash[Int, Str], then your hashes
really must be typed. An ordinary Hash that just happens to always map
strings to integers is not sufficient and will fail the type check.
You could make a looser subset of Hash with a where clause that checks
compatibility of all keys with Str and of all values with Int as well,
but that would be more expensive.

To answer your question: Hash does the Associative role which is
parameterized by the key and value type, but *in reverse order*.
Hash[Int, Str] is the type that maps Int <-- Str, just like in the
neat `my Int %pb{Str}` declaration.

Regards,
Tobias

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk

Reply via email to