Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating lists in Raku

Tags:

raku

I'm looking for a simpler solution.

I have a list of prefixes with corresponding suffixes and a list of roots.

my @prefixes = 'A'..'E';
my @suffixes = 'a'..'e';
my @roots = 1, 2;

I would like to make all the possible 'words': A1a, B1b...A2a...E2e.

my @words;
for @roots -> $r {
    for @prefixes.kv -> $i, $p {
        my $s = @suffixes[$i];
        my $word = [~] $p, $r, $s;
        @words.push: $word;
    }
}
say @words; # [A1a B1b C1c D1d E1e A2a B2b C2c D2d E2e]

I suppose that it is possible to do it much easier using something like zip or cross, but can't figure out how...

like image 562
Eugene Barsky Avatar asked Dec 27 '17 22:12

Eugene Barsky


2 Answers

My solution would be:

say @roots.map: |(@prefixes >>~>> * <<~<< @postfixes);

Create a WhateverCode for metaopping concatenation, slipping the result to get a Seq with only scalar values at the end.

like image 178
Elizabeth Mattijsen Avatar answered Oct 23 '22 09:10

Elizabeth Mattijsen


A few more ways to write it:


say @roots X[&join] (@prefixes Z @suffixes);

say @roots.map({ |(@prefixes Z @suffixes)».join($_) });

say @roots.map({ (@prefixes X~ $_) Z~ @suffixes }).flat;

say (|@prefixes xx *) Z~ (@roots X~ @suffixes);

my @formats = (@prefixes Z @suffixes).flat.map(* ~ '%s' ~ *);
say @formats X[&sprintf] @roots;

(Note: This one prints them in a different order.)


say do for @roots -> $root {
    |do for (@prefixes Z @suffixes) -> [$prefix, $suffix] {
        $prefix ~ $root ~ $suffix
    }
}
like image 20
smls Avatar answered Oct 23 '22 10:10

smls