|
| 1 | +=begin pod |
| 2 | +
|
| 3 | +=head1 Problem |
| 4 | +
|
| 5 | +Generate a string with N opening brackets (“[”) and N closing brackets (“]”), in some arbitrary order. |
| 6 | +Determine whether the generated string is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest. |
| 7 | +
|
| 8 | +=head1 More |
| 9 | +
|
| 10 | +L<http://rosettacode.org/wiki/Balanced_brackets#Perl_6> |
| 11 | +
|
| 12 | +=head1 What's interesting here? |
| 13 | +* idiomatic solutions |
| 14 | +* hyper operators |
| 15 | +* switch statement |
| 16 | +* roll |
| 17 | +* grammar |
| 18 | +
|
| 19 | +=head2 Depth counter |
| 20 | +
|
| 21 | +=end pod |
| 22 | + |
| 23 | +sub balanced($s) { |
| 24 | + my $l = 0; |
| 25 | + for $s.comb { |
| 26 | + when "]" { |
| 27 | + --$l; |
| 28 | + return False if $l < 0; |
| 29 | + } |
| 30 | + when "[" { |
| 31 | + ++$l; |
| 32 | + } |
| 33 | + } |
| 34 | + return $l == 0; |
| 35 | +} |
| 36 | + |
| 37 | +my $n = prompt "Number of brackets"; |
| 38 | +my $s = (<[ ]> xx $n).pick(*).join; |
| 39 | +say "$s {balanced($s) ?? "is" !! "is not"} well-balanced" |
| 40 | + |
| 41 | +=begin pod |
| 42 | +
|
| 43 | +=head2 FP oriented |
| 44 | +
|
| 45 | +=end pod |
| 46 | + |
| 47 | +sub balanced($s) { |
| 48 | + .none < 0 and .[*-1] == 0 |
| 49 | + given [\+] '\\' «leg« $s.comb; |
| 50 | +} |
| 51 | + |
| 52 | +my $n = prompt "Number of bracket pairs: "; |
| 53 | +my $s = <[ ]>.roll($n*2).join; |
| 54 | +say "$s { balanced($s) ?? "is" !! "is not" } well-balanced" |
| 55 | + |
| 56 | +=begin pod |
| 57 | +
|
| 58 | +=head2 String munging |
| 59 | +
|
| 60 | +=end pod |
| 61 | + |
| 62 | +sub balanced($_ is copy) { |
| 63 | + () while s:g/'[]'//; |
| 64 | + $_ eq ''; |
| 65 | +} |
| 66 | + |
| 67 | +my $n = prompt "Number of bracket pairs: "; |
| 68 | +my $s = <[ ]>.roll($n*2).join; |
| 69 | +say "$s is", ' not' xx not balanced($s)), " well-balanced"; |
| 70 | + |
| 71 | +=begin pod |
| 72 | +
|
| 73 | +=head2 Prasing with a grammar |
| 74 | +
|
| 75 | +=end pod |
| 76 | + |
| 77 | +grammar BalBrack { |
| 78 | + token TOP { ^ <balanced>* $ }; |
| 79 | + token balanced { '[]' | '[' ~ ']' <balanced> } |
| 80 | +} |
| 81 | + |
| 82 | +my $n = prompt "Number of bracket pairs: "; |
| 83 | +my $s = <[ ]>.roll($n*2).join; |
| 84 | +say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced"; |
| 85 | + |
| 86 | +=begin pod |
| 87 | +
|
| 88 | +=head1 Features used |
| 89 | +
|
| 90 | +C<roll> - L<http://perlcabal.org/syn/S32/Containers.html#roll> |
| 91 | +C<given> - L<http://perlcabal.org/syn/S04.html#Switch_statements> |
| 92 | +C<prompt> - L<http://perlcabal.org/syn/S32/IO.html#prompt> |
| 93 | +C<grammar> - L<http://perlcabal.org/syn/S05.html#Grammars> |
| 94 | +
|
| 95 | +=end pod |
| 96 | + |
| 97 | +# vim: expandtab shiftwidth=2 ft=perl6: |
0 commit comments