2017年2月27日月曜日

開発環境

Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のChapter 7(Strings)のExercises 7-1、2、3.を取り組んでみる。

Exercises 7-1、2、3.

コード(Emacs)

#!/usr/bin/env perl6

say '7-1.';
sub count($letter, $word) {
    my $count = 0;
    my $i = 0;
    while $i < $word.chars {
        $i = $word.index($letter, $i);
        last unless $i;
        $count++;
        $i++;        
    }
    $count;
}

say count('a', 'banana') == 3;
say count('a', 'bnn') == 0;

sub count1($letter, $word) {
    my $count = 0;
    for 0..$word.chars - 1 -> $i {
        $count++ if $word.substr($i, 1) eq $letter;
    }
    $count;
}

say count1('a', 'banana') == 3;
say count1('a', 'bnn') == 0;

say '7-2.';
sub is-lower (Str $char) {
    so $char ~~ /^<[a..z]>$/;
}

say not is-lower('');
say is-lower('a');
say not is-lower('ab');
say not is-lower('A');
say not is-lower('aB');

sub any-lowercase-unless(Str $string) {
    for $string.comb -> $char {
        return False unless is-lower $char;
    }
    True;
}

say 'any-lowercase-unless';
say any-lowercase-unless('');
say any-lowercase-unless('a');
say any-lowercase-unless('ab');
say not any-lowercase-unless('A');
say not any-lowercase-unless('AB');
say not any-lowercase-unless('aB');
say not any-lowercase-unless('Ab');

sub any-lowercase-flag(Str $string) {
    my $flag = True;
    for $string.comb -> $char {
        $flag &&= is-lower $char;
    }
    $flag;
}

say 'any-lowercase-flag';
say any-lowercase-flag('');
say any-lowercase-flag('a');
say any-lowercase-flag('ab');
say not any-lowercase-flag('A');
say not any-lowercase-flag('AB');
say not any-lowercase-flag('aB');
say not any-lowercase-flag('Ab');

say '7-3.';
sub rotate-word($string, $n) {
    my $result = '';
    for $string.comb {
        my $m = $_.ord + $n;
        $m -= 26 if $m > 'z'.ord;
        $result ~= $m.chr;
    }
    $result;
}

say 'rotate-word';
my $s1 = 'perl';
my $s2 = 'xyz';

say $s1;
say rotate-word $s1, 13;
say rotate-word rotate-word($s1, 13), 13;

say $s2;
say rotate-word $s2, 13;
say rotate-word rotate-word($s2, 13), 13;

入出力結果(Terminal)

$ ./sample1.pl
7-1.
True
True
True
True
7-2.
True
True
True
True
True
any-lowercase-unless
True
True
True
True
True
True
True
any-lowercase-flag
True
True
True
True
True
True
True
7-3.
rotate-word
perl
crey
perl
xyz
klm
xyz
$

0 コメント:

コメントを投稿

Comments on Google+: