Raku By Example
View me onGitHub
## is trait

multi sub trait_mod:<is>(Routine $r, :$doubles!) {
    $r.wrap({
        2 * callsame;
    });
}

sub square($x) is doubles {
    $x * $x;
}

say square 3;

## of trait

my @list of Int = 1..10000;
say @list[99].WHAT;

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

sub fib(Int $nth where * >= 0) {
  given $nth {
    when 0 { 0 }
    when 1 { 1 }
    default { fib($nth-1) + fib($nth-2) }
 }
}
say fib(3);
#say fib(-3);

subset FirstName
    of Str
  where 0 < *.chars && *.chars < 256;

sub first_name(FirstName $name){
    say "$name";
}

first_name("Wall");

subset PointLimit of Int where -10 <= * <= 10;
sub test(PointLimit $number) {
    say $number;
}
test(-5);

subset SmallInt of Int where -10 .. 10;
sub small(SmallInt $number) {
    say $number;
}

small(8);


## subtype

sub divide(Int $a,
           Int $b where { $^n != 0 }) {
    return $a / $b;
}
say divide(120, 3); # 42
# say divide(100, 0); # Type check failure

# Here is an example of using subtypes to distinguish between two candidates

multi say_short(Str $x) {
    say $x;
}
multi say_short(Str $x
                  where { $_.chars >= 12 }) {
   say substr($x, 0, 10) ~ '...';
}
say_short("Beer!");         # Beer!
say_short("BeerBeerBeer!"); # BeerBeerBe...

## Typed Parameters

# Typed Parameters Can restrict a parameter to only accept arguments of a certain type.
sub show_dist(Str $from, Str $to, Int $kms) {
    say "From $from to $to is $kms km.";
}
show_dist('Copenhagen', 'Beijing', 7305);
show_dist(7305, 'Copenhagen', 'Beijing');


## is pure

sub four-bits() is pure {
    say "pure 4 bits";
    return  <0 1> X~  <0 1> X~  <0 1> X~  <0 1>;
}

proto royal-road( Str $bits ) is pure {*}
multi royal-road( "0000" ) is pure { say "pure0000"; return 1; }
multi royal-road( "1111" ) is pure { say "pure1111"; return 1; }
multi royal-road( Str $bits ) is pure { say "purexxxx"; return 0; }

BEGIN { say ‘Begin’ }
say ‘Start’;
say royal-road("1010");
my %royal-road-hash = four-bits().map: { $^þ => royal-road( $^þ ) };

say %royal-road-hash;