Raku By Example
View me onGitHub
## classify into
my @list = (
    <Camelia 5>,
    <Camelia 6>,
    <Camelia 7>,
    <Amelia 1>,
    <Amelia 2>,
    <Amelia 3>
    );

my %hash = @list.classify: *.[0], as => *.[1];
say %hash;  # {Amelia => [1 2 3], Camelia => [5 6 7]}
@list.classify: *.[0], :into(my %h), :as( *.[1] );
say %h;


## classify

#.say for slurp("README.txt")\           # whole file into string
#         .words()\                      # split into list of words
#         .classify( *.Str );

my @a = slurp("README.txt").words;
# .say  for @a.classify( *.Str );
# output:
#  可见输出的是一个散列
# that => that that that that that that that that that that that
# the => the the the the the the the the the the the the the the ...
# is => is is is is is is is is is is is is is is is is

my %hash = @a.classify( *.Str );
for %hash.sort({-.value.elems}).hash.kv.[^20] -> $key, $value {
    say $key ,"\t", $value.elems;
}

## count

my $a = ('a' .. 'z').roll(1000000);
say .key, ' => ', .value for $a.cache.classify(*.Str).map({.key => .value.elems}).sort({-.value});
say now - INIT now;

## grouby by substring

my @lines = "test.txt".IO.lines;
.say for @lines.classify: {.split('_')[0..2].join("_")};

## 怎样在一个数组中找出每个元素重复的次数呢?将每个元素和重复次数对应输出。
my @a = 1,2,6,6,6,6,9,9;
my %hash = @a.classify(*.Str);
for %hash.kv -> $k,$v {say "$k    | $v.elems()"}

#----------------------------------------------------


# 统计文件中出现次数最多的前 10 个单词:
.say for slurp("README.md")\             # whole file into string
         .words()\                       # split into list of words
         .classify( *.Str )\             # group words with multiplicity
         .map({;.key => .value.elems })\ # turn lists into lengths
         .sort( { -.value } )\           # sort descending
         .[ ^10 ];                       # 10 most common words


# Output:
# the => 40
# to => 21
# is => 16


# 根据字符串的字符个数分类
my @names = <Patrick Jonathan Larry Moritz Audrey>;
say .key, "\t", ~.values
    for @names.classify( *.chars );

# Output:
# 7	Patrick
# 8	Jonathan
# 5	Larry
# 6	Moritz Audrey


# 根据截取的字符串分组
my @lines = "README.txt".IO.lines;
.say for @lines.classify: {.split('_')[0..2].join("_")};