Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively building nested hash from a simple array

Tags:

raku

Got this:

my @list = <one two three>;

my %hash;
my $item1 = @list.shift;
%hash{$item1} = {$item1 => 1};

my $item2 = @list.shift;
%hash{$item1} = {$item2 => 1};

my $item3 = @list.shift;
%hash{$item1}{$item2} = {$item3 => 1};

say %hash;

Outputs this desired data structure:

{one => {two => {three => 1}}}

Obviously, this would be better if it were recursive, so I wrote this:

sub get-hash(%parent-hash, $last-item, *@list) {
    my $item = @list.shift;
    %parent-hash{$last-item} = { $item => 1 };
    get-hash(%parent-hash{$last-item}, $item, @list) if @list;

    return %parent-hash<root>;
}

%hash = get-hash({}, 'root', @list2);

Output:

{one => {two => {three => 1}}}

Though it works, it feels inelegant, especially having to pass in a root argument to the sub and then removing it. Any suggestions?

like image 734
StevieD Avatar asked Oct 24 '25 19:10

StevieD


1 Answers

In the upcoming Raku version, there's a neat way to do this:

use v6.e.PREVIEW;
my @list = <one two three>;
my %hash;
%hash{||@list} = 1;
say %hash;

The || indicates that you want to use the list as multi-dimensional hash keys.

If you want to stick to things in the current released language versions, you can still call the operator directly, since it's only the syntax sugar that is missing:

my @list = <one two three>;
my %hash;
postcircumfix:<{; }>(%hash, @list) = 1;
say %hash

The output in either case is as you wish:

{one => {two => {three => 1}}}
like image 178
Jonathan Worthington Avatar answered Oct 28 '25 06:10

Jonathan Worthington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!