Skip to content

Instantly share code, notes, and snippets.

@dwarring
Created November 19, 2013 20:52
Show Gist options
  • Save dwarring/7552347 to your computer and use it in GitHub Desktop.
Save dwarring/7552347 to your computer and use it in GitHub Desktop.
grammar Picker {
rule combination($rx, $narity) {
:my %*PICKED;
<choose($rx)> ** $narity
}
rule choose($rx) {
$<choice>=$rx <?{
if %*PICKED{ ~$<choice> } {
warn("oops, trying to repick: " ~$<choice>);
False;
}
else {
%*PICKED{ ~$<choice> } = True;
}
}>
}
}
grammar Colors is Picker {
token color {[red|orange|yellow|green|blue|indigo|violet]<!ww>}
rule one-or-more-colors {
$<choices>=<combination( rx[ <color> ], 1..* )>
}
rule any-two-colors {
$<choices>=<combination( rx[ <color> ], 2..2 )>
}
}
say Colors.parse(<red blue green>, :rule<one-or-more-colors>);
say Colors.parse(<red blue green blue>, :rule<one-or-more-colors>);
say Colors.parse(<red>, :rule<any-two-colors>);
say Colors.parse(<red blue>, :rule<any-two-colors>);
say Colors.parse(<red blue green>, :rule<any-two-colors>);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment