aboutsummaryrefslogtreecommitdiff
path: root/challenge-029
diff options
context:
space:
mode:
authorJoelle Maslak <jmaslak@antelope.net>2019-10-12 16:08:15 -0600
committerJoelle Maslak <jmaslak@antelope.net>2019-10-12 16:08:15 -0600
commit4efc7d00b5927c4d1a7b657b3984008ee35e970f (patch)
treee7128ab5442cc1d70e319f22f7ec760fba796e61 /challenge-029
parent9abb23c578cb523a2afddacd2ac03b4a72b9f52e (diff)
downloadperlweeklychallenge-club-4efc7d00b5927c4d1a7b657b3984008ee35e970f.tar.gz
perlweeklychallenge-club-4efc7d00b5927c4d1a7b657b3984008ee35e970f.tar.bz2
perlweeklychallenge-club-4efc7d00b5927c4d1a7b657b3984008ee35e970f.zip
Joelle's solution to 29.1 in Perl 6
Diffstat (limited to 'challenge-029')
-rwxr-xr-xchallenge-029/joelle-maslak/perl6/ch-1.p673
1 files changed, 73 insertions, 0 deletions
diff --git a/challenge-029/joelle-maslak/perl6/ch-1.p6 b/challenge-029/joelle-maslak/perl6/ch-1.p6
new file mode 100755
index 0000000000..0234c8deb9
--- /dev/null
+++ b/challenge-029/joelle-maslak/perl6/ch-1.p6
@@ -0,0 +1,73 @@
+#!/usr/bin/env perl6
+use v6;
+
+# This handles the following:
+#
+# a{1,2}
+# a{1,2{3,4}}{5,6}b
+#
+# And similar versions. So, yes, you can nest and have multiple
+# curlies. Note there is no way to "quote" commas or curlies at this
+# time, but they would be reasonably straightforward to add (Perl 6 is
+# awesome). Now to try to figure out how to do this in P5, without the
+# awesome grammars...
+#
+
+grammar Expansion {
+ rule TOP {
+ ^
+ <element>*
+ $
+ }
+ token element { <string> | <curly> }
+ token string { <-[ \{ \} ]>+ }
+ token curly { \{ <option>+ % ',' \} }
+ token option { <innerstr> | <curly> }
+ token innerstr { <-[ \{ \} \, ]>* }
+}
+
+
+sub MAIN(Str:D $str) {
+ my $expanded = expand($str);
+
+ say $expanded.sort.unique.join("\n");
+}
+
+sub expand($str) {
+ my $parse = Expansion.parse($str);
+ die "Invalid String" unless $parse.defined;
+
+ return expansion([''], $parse);
+}
+
+# The magic happens here. Basically it recursively calls itself as it
+# descends the tree. Have I mentioned how much I love Perl 6 grammars?
+#
+# Note that string token is different than the innerstr, which looks
+# like duplicated code (I'm willing to live with a couple lines here)
+# but is not quite since string and innerstring *are* different - the
+# outter strings (outside any curlies) allows commas.
+sub expansion(@arr is copy, $tree) {
+ if $tree<element>:exists {
+ # Handle each element.
+ for @($tree<element>) -> $ele {
+ @arr = expansion(@arr, $ele);
+ }
+ return @arr;
+ } elsif $tree<string>:exists {
+ return @arr.map: { $_ ~ $tree<string> };
+ } elsif $tree<innerstr>:exists {
+ return @arr.map: { $_ ~ $tree<innerstr> };
+ } elsif $tree<curly>:exists {
+ my @arr-copy = @arr;
+ @arr = [];
+ for @($tree<curly><option>) -> $ele {
+ @arr.append: expansion(@arr-copy, $ele);
+ }
+ return @arr;
+ } else {
+ die;
+ }
+
+}
+