Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I “flatten” a list of lists in perl 6?

Tags:

raku

Let's say I want all permutations of 2 letters out of a, b and c.

I can do:

my @perm = <a b c>.combinations(2)».permutations;
say @perm;
# [((a b) (b a)) ((a c) (c a)) ((b c) (c b))]

which is close, but not exactly what I need. How do I “flatten” this so that I get:

# [(a b) (b a) (a c) (c a) (b c) (c b)]

?

like image 735
mscha Avatar asked May 11 '16 20:05

mscha


2 Answers

See also "a better way to accomplish what I (OP) wanted".

See also "Some possible solutions" answer to "How can I completely flatten a Raku list (of lists (of lists) … )" question.

Add a subscript

my \perm = <a b c>.combinations(2)».permutations;
say perm;       # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*];    # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*;*];  # ((a b) (b a) (a c) (c a) (b c) (c b))
say perm[*;*;*] # (a b b a a c c a b c c b)

Notes

I used a non-sigil'd variable because I think it's a bit clearer what's going on for those who don't know Raku.

I didn't append the subscript to the original expression but I could have:

my \perm = <a b c>.combinations(2)».permutations[*;*];
say perm;       # ((a b) (b a) (a c) (c a) (b c) (c b))
like image 14
raiph Avatar answered Nov 07 '22 12:11

raiph


Ultimately, you are building your list the wrong way to begin with. You can slip your permutations into the outer list like this.

<a b c>.combinations(2).map(|*.permutations);

Which yields the following list

((a b) (b a) (a c) (c a) (b c) (c b)) 

According to the Bench module, this is about 300% faster than doing

<a b c>.combinations(2).map(*.permutations)[*;*]
like image 10
Joshua Avatar answered Nov 07 '22 13:11

Joshua