Skip to content

Instantly share code, notes, and snippets.

@masak
Created December 14, 2014 21:51
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 masak/01c4469169dc88e2c114 to your computer and use it in GitHub Desktop.
Save masak/01c4469169dc88e2c114 to your computer and use it in GitHub Desktop.
FP version of the animal guessing game, http://irclog.perlgeek.de/perl6/2014-12-13#i_9800695
say "Play 'Guess the animal'";
say "Think of an animal and the computer will try to guess it.";
my &ask = decision("Does it swim", animal("fish"), animal("bird"));
while say("") && is-prompt-yes "Are you thinking of an animal? " {
ask;
}
sub is-prompt-yes($question) {
my $answer = prompt($question);
if !defined $answer {
say("");
exit;
}
return so $answer.lc eq 'y' | 'yes';
}
sub decision($q, $yes, $no) {
-> {
if is-prompt-yes("$q? ") {
$yes()();
}
else {
$no()();
}
}
}
sub animal($guess) {
my $node = {
if is-prompt-yes("Is it a $guess? ") {
say "Why not try another animal?";
}
else {
my $actual = prompt "The animal you were thinking of was a? ";
say "Please type a question that would distinguish a $actual from a $guess";
my $q = (prompt "? ").trim.subst(/\?$/, "");
if is-prompt-yes "For a $actual the answer would be? " {
$node = decision($q, animal($actual), animal($guess));
}
else {
$node = decision($q, animal($guess), animal($actual));
}
}
}
return { $node };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment