Balanced brackets
AUTHOR
Filip Sergot
Generate a string with N opening brackets (β[β) and N closing brackets (β]β), in some arbitrary order.
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.
More
http://rosettacode.org/wiki/Balanced_brackets#Raku
What's interesting here?
idiomatic solutions
hyper operators
switch statement
roll
grammar
Features used
given
- https://doc.perl6.org/syntax/given#language_documentation_Control_Flowprompt
- https://doc.perl6.org/routine/promptgrammar
- https://doc.perl6.org/language/grammars
Depth counter
FP oriented
String munging
Parsing with a grammar
use v6;
my $n = prompt "Number of bracket pairs: ";
{
sub balanced($s) {
my $l = 0;
for $s.comb {
when "]" {
--$l;
return False if $l < 0;
}
when "[" {
++$l;
}
}
return $l == 0;
}
my $s = (<[ ]> xx $n).pick(*).join;
say "Using depth counter method";
say "$s {balanced($s) ?? "is" !! "is not"} well-balanced";
}
{
sub balanced($s) {
.none < 0 and .[*-1] == 0
given ([\+] '\\' Β«legΒ« $s.comb).cache;
}
my $s = <[ ]>.roll($n*2).join;
say "Using an FP oriented method";
say "$s { balanced($s) ?? "is" !! "is not" } well-balanced";
}
{
sub balanced($_ is copy) {
s:g/'[]'// while m/'[]'/;
$_ eq '';
}
my $s = <[ ]>.roll($n*2).join;
say "Using a string munging method";
say "$s is", ' not' xx not balanced($s), " well-balanced";
}
{
grammar BalBrack {
token TOP { ^ <balanced>* $ };
token balanced { '[]' | '[' ~ ']' <balanced> }
}
my $s = <[ ]>.roll($n*2).join;
say "Parsing brackets with a grammer";
say "$s { BalBrack.parse($s) ?? "is" !! "is not" } well-balanced";
}
# vim: expandtab shiftwidth=4 ft=perl6