Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you assign values to a Hash key without concomitant boxing (i.e. itemization)?

Tags:

syntax

raku

Coming from this SO question, I'm trying to have a List (or non-scalar thing, in general) as the value assigned to a Hash key, this way:

my %syns-by-name does Associative[Str,List] = Bq => ("Bq", "becquerel", "becquerels");
my Str  @syns = %syns-by-name<Bq>;

That does not work, however. Lists are itemized before being assigned, so the value is always a Scalar. You need to do a workaround to actually make this work:

my %syns-by-name does Associative[Str,List] = Bq => ("Bq", "becquerel", "becquerels");

my @list := <C coulomb coulombs>;
%syns-by-name<C> := @list;

my Str  @syns = %syns-by-name<C>;
say @syns;

This returns what we were looking for, a list. However, how could we do that directly on the assignment and convince a list is a list and not an itemized list?

like image 619
jjmerelo Avatar asked Dec 27 '20 09:12

jjmerelo


1 Answers

Assuming you don't need mutation afterwards, use a Map instead of a Hash.

my %syns-by-name is Map = Bq => ("Bq", "becquerel", "becquerels");
my Str @syns = %syns-by-name<Bq>;
say @syns; # [Bq becquerel becquerels]

Since there's no expectation that entries in a Map are assignable, it doesn't create Scalar containers for the values.

like image 122
Jonathan Worthington Avatar answered Feb 07 '23 02:02

Jonathan Worthington