Skip to content

Instantly share code, notes, and snippets.

@AlexDaniel
Last active February 17, 2016 16:52
Show Gist options
  • Save AlexDaniel/1e2d1c50963d37c5d43a to your computer and use it in GitHub Desktop.
Save AlexDaniel/1e2d1c50963d37c5d43a to your computer and use it in GitHub Desktop.
Array splits

Is there a cute Perl 6 way to take an array (say ‘a’..‘d’) and get all head/tail partitions of it (e.g. (<a>, <b c d>), (<a b>, <c d>), (<a b c>, <d>))?

Sure! Pick one:

my @a = a..e; say (@a[^$_, $_..*] for 1..^@a);
my @b = a..e; say (1..^@b).map: {@b[^$_, $_..*]};
my @c = a..e; say (@c.rotor($_, ∞, :partial) for 1..^@c);
my @z = a..e; say @z[0..*-2].keys.map: {@z[0..$_, $_^..*]}; # same as b
my @d = a..e; say (1..^@d).map: {@d.rotor: $_, ∞, :partial};
my @e = a..e; say (@e.head($_), @e.tail(@e - $_) for 1..^@e);
my @f = a..e; say (|@f.rotor: $_, @f - $_ for 1..^@f).rotor: 2;
my @g = a..e; say @g.keys.map: {@g[0..$_, $_^..*] if $_ < @g.end};
my @h = a..e; say @h.keys.map: {@h.head($_), @h.tail(@h - $_) if $_};
my @i = a..e; say @i.rotor(|(1..^@i Z (@i-1…0) »=>» -@i), ∞).rotor: 2;
my @j = a..e; say ([\,] @j) Z (([\,] @j[1..*].reverse.reverse).reverse;

All should produce same output:

(((a) (b c d e)) ((a b) (c d e)) ((a b c) (d e)) ((a b c d) (e)))

However, not all of them are identical. Some may produce Seqs.

@MadcapJake
Copy link

I remembered this from a few weeks back and with it created an example of utilizing Test::Lab. What better language than Perl 6 to have a framework for examining refactors/variations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment