Skip to content

Instantly share code, notes, and snippets.

@ahalbert
Created August 15, 2016 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahalbert/5cd22fafc0c383c70da0fadc0a50d614 to your computer and use it in GitHub Desktop.
Save ahalbert/5cd22fafc0c383c70da0fadc0a50d614 to your computer and use it in GitHub Desktop.
sub groupby(@elements is copy, $key={ $_ }) is export {
gather {
my @rest = @elements.Array;
while ?@rest {
my $head = $key(shift @rest);
@rest = (@rest ==> grep { $head ne $key($_)});
take (@rest ==> grep { $head eq $key($_)}, $head);
}
}
}
say groupby(['a','b','a','a','a','b','b','c','a']); #((a) (b) (c))
Should be ((a a a a a) (b b b) (c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment