编程练习解决方案汇总
立即解锁
发布时间: 2025-08-22 00:57:38 阅读量: 1 订阅数: 4 


Perl 6编程入门与实践
### 编程练习解决方案汇总
#### 1. 随机单词练习
在处理随机单词的问题时,首先可以通过以下代码获取文本内容并进行初步处理:
```perl6
map { | process-line $_},
("emma.txt".IO.lines)[0..1999];
```
若要去除文本头部信息,由于书籍实际内容从第 254 行开始,可使用以下代码:
```perl6
my @unknown-words = unique grep {$_ ∉ $word-list},
grep { $_ },
map { | process-line $_},
("emma.txt".IO.lines)[253..1999];
```
并从 `process-line` 函数中移除跳过头部的代码。
在使用 `BisectSearch` 模块时,由于当前模块进行的是字符串比较,而我们需要数值比较,最佳解决方案是复制该子例程并修改为进行数值比较。新的多子例程可以有相同的名称,但签名不同,新多子例程的第一个参数应为 `Int` 而非 `Str`。以下是使用该模块的程序示例:
```perl6
use lib ".";
use BisectSearch;
my %histogram;
sub process-line(Str $line is copy) {
$line ~~ s:g/<[-']>/ /;
$line ~~ s:g/<[;:,!?.()"_`]>//;
$line = $line.lc;
return $line.words;
}
%histogram{$_}++ for grep {$_},
map { | process-line $_},
("emma.txt".IO.lines)[253..*];
my (@words, @freqs);
my $total_freq = 0;
for %histogram.kv -> $word, $freq {
$total_freq += $freq;
push @words, $word;
push @freqs, $total_freq;
}
my $rand_int = $total_freq.rand.Int;
my $idx = bisect $rand_int, @freqs;
say @words[$idx];
```
#### 2. 马尔可夫分析练习
在介绍马尔可夫分析练习的解决方案之前,先了解一下 `MAIN` 子例程。程序传递的参数通常存储在 `@*ARGS` 特殊数组中,我们可以遍历该数组来获取参数。例如:
```bash
$ perl6 -e 'say $_ for reverse @*ARGS' one two three
```
输出结果为:
```
three
two
one
```
另一种方式是使用 `MAIN` 子例程,若程序中存在名为 `MAIN` 的子例程,程序将首先执行该子例程,其参数即为传递给程序的参数。`MAIN` 子例程的签名可用于获取参数并检查其有效性。示例如下:
```perl6
sub MAIN (Str $book, Int $word-count, Int $order = 2,
Int $start-line = 0) {
# body of subroutine here
}
```
若传递给程序的参数与 `MAIN` 签名不匹配,程序将打印自动生成的使用信息后终止。
以下是对文本文件进行马尔可夫分析的解决方案:
```perl6
my %prefixes;
sub MAIN (Str $book, Int $word-count, Int $order = 2,
Int $start-line = 0) {
process-line($order, $_) for ($book.IO.lines)[$start-line..*];
say make-text($order, $word-count);
}
sub process-line($order, Str $line is copy) {
$line ~~ s:g/<[-']>/ /;
$line ~~ s:g/<[;:,!?.()"_`]>//; # removing punctuation symbols
$line = $line.lc; # setting string to lowercase
return unless $line ~~ /\w/;
process-words($order, $line.words);
}
sub process-words ($order, @new-words) {
state @word-buffer = ();
push @word-buffer, |@new-words;
while (@word-buffer.elems >= $order * 2) {
my $key = @word-buffer.shift ~ " " ~
(join ' ', @word-buffer[0..$order - 2]);
my $value = @word-buffer[$order -1];
push %prefixes{$key}, $value;
}
}
sub make-text (Int $order, Int $w-count) {
my @prefix = %prefixes.keys.pick.words;
my $count = 0;
my $text = join " ", @prefix;
while $count <= $w-count {
my @possible-suffixes = |%prefixes{join " ", @prefix};
last unless @possible-suffixes;
my $new-word = |@possible-suffixes.pick;
$text ~= " $new-word";
shift @prefix;
push @prefix, |$new-word;
$co
```
0
0
复制全文
相关推荐










