Skip to content

Instantly share code, notes, and snippets.

@tene
Created December 17, 2009 16:58
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 tene/258871 to your computer and use it in GitHub Desktop.
Save tene/258871 to your computer and use it in GitHub Desktop.
grammar Question::Grammar {
rule TOP {
<question>+
{*}
}
token question {
<header>
<answer>+
{*}
}
token header {
^^ $<type>=['pickone'|'pickmany'] ':' <.ws> $<text>=[\N*] \n
}
token answer {
^^ <.ws> $<correct>=['ac'|'ai'] ':' <.ws> $<text>=[\N*] \n {*}
}
}
class Question {
class Answer {
has $.text is rw;
has $.correct is rw;
}
has $.text is rw;
has $.type is rw;
has Question::Answer @.answers is rw;
method ask {
my %hints = (
pickmany => "Choose all that are true, separated by spaces",
pickone => "Choose the one item that is correct",
);
say "\n{%hints{$.type}}\n";
say $.text;
for @.answers.kv -> $i, $a {
say "$i) {$a.text}";
}
print "> ";
my $line = $*IN.get();
my @answers = $line.comb(/<digit>+/)>>.Int.sort;
my @correct = @.answers.kv.map({ $^value.correct ?? $^key !! () });
if @correct ~~ @answers {
say "Yay, you got it right!";
return 1;
}
else {
say "Oops... you got it wrong. :(";
return 0;
}
}
}
class Question::Actions {
method answer($/) {
my $correct = ~$<correct> eq 'ac';
make Question::Answer.new(
:correct($correct),
:text(~$<text>),
);
}
method question($/) {
my $q = Question.new();
$q.text = $<header><text>;
$q.type = $<header><type>;
for $<answer> {
$q.answers.push($_.ast);
}
make $q;
}
method TOP($/) {
my @qs = gather for $<question> {
take $_.ast;
}
make @qs;
}
}
my $text = Q {
pickmany: Which items are food?
ac: Rice
ac: Orange
ac: Mushroom
ai: Shoes
pickone: Which item is a color?
ac: Orange
ai: Shoes
ai: Mushroom
ai: Rice
};
my $actions = Question::Actions.new();
my @questions = Question::Grammar.parse($text, :action($actions)).ast;
my @results = @questions.map(*.ask);
say "\nFinal score: " ~ [+] @results;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment