Raku By Example
View me onGitHub
## zip

my @a=1,2,3;
my @b=4,5,6;
my @c=7,8,9;
for zip(@a; @b; @c) -> $a, $b, $c {say $a,$b,$c;}

## X 

say 0..9 X~ 'a' .. 'z';

## Z

# Loop over multiple arrays (or lists or tuples or whatever they're called in your language) and print the ith element of each. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. 

# For this example, loop over the arrays (a,b,c), (A,B,C) and (1,2,3) to produce the output 
# aA1
# bB2
# cC3

for <a b c> Z <A B C> Z 1, 2, 3 -> $x, $y, $z {
   say $x, $y, $z;
}

# The Z operator stops emitting items as soon as the shortest input list is exhausted. However, short lists are easily extended by replicating all or part of the list, or by appending any kind of lazy list generator to supply default values as necessary. 

# Note that we can also factor out the concatenation by making the Z metaoperator apply the ~ concatenation operator across each triple: 
for <a b c> Z~ <A B C> Z~ 1, 2, 3 -> $line {
   say $line;
}

# We could also use the zip-to-string with the reduction metaoperator: 
.say for [Z~] [<a b c>], [<A B C>], [1,2,3]

## add three column
my @lines = slurp('3col.txt');
for @lines -> $line {
   my @b = $line.comb(/\d+/);
   say "@b[]";
   say "-" x 45;
}

my $fh = open('3col.txt');
# say [+] ($fh.lines».words).[2];
my @l = $fh.lines».comb(/\d+/);
say @l.elems;


## 自定义中缀运算符
# 该源文件必须保存为 UTF8 格式 才不会报 UTF-8 错误, 即使是中文注释
sub infix:<>(@array, $ins) {
    @array.splice(+@array / 2, 0, $ins);
    return @array;
}

my @a = 1,2,4,5;
say @a3;

## 2次幂

class PowerBy2 {
    has $.number;

	method power_by2() {
	    return  $.number ** 2;
	}
}

my  $test = PowerBy2.new(number=>10);
say $test.power_by2;

my @a = <1 2 3 4>;
my @b = @a».power_by2;
say @b;

## max width

my @scores = 'Ana' => 8, 'Dave' => 6, 'Charlie' => 4, 'Beth' => 4;

my $screen-width = 30;

my $label-area-width = 1 + [max] @scores».key».chars;
my $max-score = [max] @scores».value;
my $unit = ($screen-width - $label-area-width) / $max-score;
my $format = '%- ' ~ $label-area-width ~ "s%s\n";

for @scores {
    printf $format, .key, 'X' x ($unit * .value);
}

## zip three elements

my @a=1,2,3;
my @b=4,5,6;
my @c=7,8,9;
for zip(@a; @b; @c) -> $a, $b, $c {say $a,$b,$c;}

## [-]

say [-] <10 5 3>;
say [-] 10;

## 扑克牌

my @suits  = <♣ ♢ ♡ ♠>;
my @ranks  = 2..10, <J Q K A>;

# concatenate each rank with each suit (2♣ 2♢ 2♡ ... A♠)
my @deck = @ranks X~ @suits;

# build a hash of card names to point values
# 52 张牌, 4 种花色, A 的值为 11 , J、Q、K 为 10
my %points = @deck Z @( (2..10, 10, 10, 10, 11) Xxx 4 );

# 把牌打乱
@deck .= pick(*); # shuffle the deck
my @hand = @deck.splice(0, 5); # 抓取前 5 张牌
say ~@hand; #  显示抓取的是哪 5 张
say [+] %points{@hand}; # 这 5 张牌面的值加起来是多少