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

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

See Also

100-doors.pl

100 Doors

24-game.pl

24 game

accumulator-factory.pl

Accumulator factory

ackermann-function.pl

Ackermann function

arbitrary-precision-integers.pl

Arbitrary-precision integers (included)

binomial-coefficient.pl

Binomial Coefficient

copy-a-string.pl

Copy a string

create-a-two-dimensional-array-at-runtime.pl

Create a two-dimensional array at runtime

hailstone-sequence.pl

Hailstone sequence

last-fridays-of-year.pl

Last fridays of the year

prime-decomposition.pl

Prime decomposition

README.md

The Camelia image is copyright 2009 by Larry Wall. "Raku" is trademark of the Yet Another Society. All rights reserved.