Skip to content

Instantly share code, notes, and snippets.

@MattOates
Last active December 24, 2015 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattOates/62a5a3d4f86333939bbf to your computer and use it in GitHub Desktop.
Save MattOates/62a5a3d4f86333939bbf to your computer and use it in GitHub Desktop.
Create a Markov parody of some input text. Makes use of KeyBag rolls.
#!/usr/bin/env perl6
use v6;
sub add-to-model (%model,$word,$trailing) {
if not %model.exists($word) {
%model{$word} = KeyBag.new;
}
%model{$word}{$trailing}++;
}
sub MAIN (Int :$generate = 100, Str :$start = "The") {
#Previous word read in
my $previous;
#Markovian bag model generated from input file Hash<Str=>KeyBag>
my %model := Hash.new;
#While we have lines read them
while my $line = $*IN.get {
#Add the words to the model
for $line.words -> $word {
if not $previous {
$previous = $word;
next;
}
add-to-model(%model,$previous,$word);
$previous = $word;
}
}
#Generate N words using the markov bag model
#Pick a random start word
my $emit = $start;
for ^$generate {
print "$emit ";
#Pick the next word weighted by the current word being emitted
$emit = %model{$emit}.roll;
if not $emit {
$emit = %model.keys.roll;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment