Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a list of 2-element lists into a hash?

Tags:

raku

I have a list of two-element lists, like what you'd get for example by (1..5) Z (20..24), that I want to make into a hash (in this example, what you get by {1 => 20, 2 => 21, 3 => 22, 4 => 23, 5 =>24}. I could do it "by hand", but that isn't too elegant, and I'm sure Raku has a idiomatic way of doing it. The inelegant alternative I come up with is:

my @a = (1..5) Z (20..24);
my %a;
for @a -> @x {
   %a{@x[0]} = @x[1];
like image 963
vonbrand Avatar asked Mar 28 '20 20:03

vonbrand


1 Answers

my %h = (1..5) Z=> (20..24);
say %h;  # {1 => 20, 2 => 21, 3 => 22, 4 => 23, 5 => 24}

The Z meta-operator takes an operator as part of its name, and it defaults to ,, thus creating lists by default. If you add the Pair constructor (aka fat-comma), then you create a list of Pairs, which you can feed into a Hash.

An alternate solution would be to flatten the result of Z:

my %h = flat (1..5) Z (20..24);
like image 166
Elizabeth Mattijsen Avatar answered Oct 20 '22 23:10

Elizabeth Mattijsen