Course of Raku / Addendum 🆕 / Working with data / Lists, arrays, and hashes / Exercises / Merge two inventories
Solution: Merge two inventories
Here is a possible solution to the task.
Code
my %shop-a = apples => 3, pears => 2;
my %shop-b = apples => 4, plums => 5;
my %total;
for %shop-a, %shop-b -> %shop {
%total{$_} += %shop{$_} for %shop.keys;
}
say %total.sort.map({ "{.key}: {.value}" }).join(', ');🦋 You can find the source code in the file merge-inventories.raku.
Output
apples: 7, pears: 2, plums: 5Comments
Looping over both hashes and doing
%total{$_} += ...adds each quantity into the running total, whether or not the key was seen before — a missing key starts at zero.%total.sortorders the pairs by key, and the.mapformats each askey: valuebefore they are joined.