2017年5月29日月曜日

開発環境

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 11(Case Study: Data Structure Selection)の Markov Analysis、Exercise: 7-1、2、3.を取り組んでみる。

Exercise: 7-1、2、3.

コード(Emacs)

#!/usr/bin/env perl6
# -*- coding: utf-8 -*-

sub make-words($filename) {
    my @words;
    for map { grep {$_.defined}, $_.words}, $filename.IO.lines -> @words0 {
        @words.push(|@words0);
    };
    return @words;
}

sub make-markov(@words, $length) {    
    my %markov;
    for 0..@words.end - (2 * $length + 1) {
        my $prefix = [~] map {$_ ~ ' '}, @words[$_..$_ + $length - 1];
        my $suffix = [~] map {$_ ~ ' '}, @words[$_ + $length..$_ + 2 * $length - 1];
        if %markov{$prefix}.defined {
            %markov{$prefix} (|)= set ($suffix);
        } else {
            %markov{$prefix} = set ($suffix);
        }
    }
    return %markov;
}

sub make-text(%markov, $count) {
    my $prefix = %markov.keys.pick(1);
    my $text = '';
    for 0..$count {
        my $suffix = %markov{$prefix}.pick(1);
        $text ~= $prefix ~ $suffix;
        $prefix = $suffix;
    }
    return $text;
}

my @words = make-words('emma.txt');

for <2 5> {
    say $_;
    my %markov = make-markov(@words, $_);
    say make-text(%markov, 10);
}

入出力結果(Terminal, REPL)

$ ./sample7.pl
2
be spared, to his to his father, and father, and her very her very differently affected. differently affected. Donwell and Donwell and Highbury, the Highbury, the large and large and populous village, populous village, almost amounting almost amounting to a to a very good 
5
to ask questions, to speak more openly than might have more openly than might have been strictly correct.--I feel that been strictly correct.--I feel that I should certainly have been I should certainly have been impertinent.” “Oh!” cried Jane, with impertinent.” “Oh!” cried Jane, with a blush and an hesitation a blush and an hesitation which Emma thought infinitely more which Emma thought infinitely more becoming to her than all becoming to her than all the elegance of all her the elegance of all her usual composure--“there would have been usual composure--“there would have been no danger. The danger would no danger. The danger would have been of my wearying 
$

0 コメント:

コメントを投稿

Comments on Google+: