開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- Perl 6 (プログラミング言語)
- Rakudo(コンパイラ、実装)
Think Perl 6: How to Think Like a Computer Scientist (Laurent Rosenfeld(著)、Allen B. Downey(著)、Oreilly & Associates Inc)のPart 1(Starting with the basics)、Chapter 7(Strings)の Exercise 7-1、7-3.を取り組んでみる。
Exercise 7-1、7-3.
コード(Emacs)
#!/usr/bin/env perl6 # -*- coding: utf-8 -*- say '1.'; sub count($word, $letter) { my $count = 0; my $i = 0; while True { $i = $word.index($letter, $i); last unless defined $i; $i++; $count++; } $count; } say 'count'; say 0 == count '', 'a'; say 1 == count 'a', 'a'; say 0 == count 'b', 'a'; say 3 == count 'banana', 'a'; say 0 == count 'bnn', 'a'; say 0 == count '日本語', 'a'; say 2 == count '日本語abcde日本語', '日'; sub count1($word, $letter) { my $count = 0; for 0..($word.chars - 1) { $count++ if $word.substr($_, 1) eq $letter; } $count; } say 'count1'; say 0 == count1 '', 'a'; say 1 == count1 'a', 'a'; say 0 == count1 'b', 'a'; say 3 == count1 'banana', 'a'; say 0 == count1 'bnn', 'a'; say 0 == count1 '日本語', 'a'; say 2 == count1 '日本語abcde日本語', '日'; say '3.'; sub rotate-letter($letter, $n) { my $m = $n % 26; $m = $m + 26 if $m < 0; my $o = $letter.ord + $m; if $letter ~~ /<[a..z]>/ { return ($o - 26).chr if 'z'.ord < $o; return $o.chr; } if $letter ~~ /<[A..Z]>/ { return ($o - 26).chr if 'Z'.ord < $o; return $o.chr; } else { return $letter; } } sub rotate-word($word, $n) { my $word0 = ''; for $word.comb -> $letter { $word0 ~= rotate-letter $letter, $n; } $word0; } say rotate-word('A', 3) eq 'D'; say rotate-word('Z', 1) eq 'A'; say rotate-word('cheer', 7) eq 'jolly'; say rotate-word('melon', -10) eq 'cubed'; say rotate-word('IBM', -1) eq 'HAL'; say rotate-word(rotate-word('Think Perl 6', 13), 13) eq 'Think Perl 6';
入出力結果(Terminal, REPL)
$ ./sample1.pl 1. count True True True True True True True count1 True True True True True True True 3. True True True True True True $
0 コメント:
コメントを投稿