Balanced brackets: Difference between revisions

Content added Content deleted
m (→‎{{header|Phix}}: added syntax colouring, marked p2js compatible)
Line 5,503: Line 5,503:
][]]][[[ NOT OK
][]]][[[ NOT OK
[[[][]]] OK
[[[][]]] OK
</pre>

=={{header|Picat}}==
Here are two approaches: one "traditional" and one using DCGs.
<lang picat> go ?=>
go1,
go_dcg,
nl.
go => true.

% "Traditional" approach
go1 ?=>
tests(Tests),
member(Test,Tests),
printf("%s: ", Test),
( balanced_brackets(Test) ->
println("OK")
;
println("NOT OK")
),
fail,
nl.
go1 => true.

% DCG
go_dcg ?=>
tests(Tests),
foreach(Test in Tests)
printf("%s: ", Test),
if balanced(Test,[]) then
println("OK")
else
println("NOT OK")
end
end,
nl.
go_dcg => true.

% Check if a string of [] is balanced
balanced_brackets(B) =>
C = 0,
foreach(I in 1..B.length, C >= 0)
C:= C + cond(B[I] = '[', 1, -1)
end,
C == 0.

% Using DCG
balanced --> "".
balanced --> "[", balanced, "]", balanced.

tests(["","[]", "[][]", "[[][]]", "][",
"][][", "[]][[]", "[][][][][][][][][][]",
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]",
"[][[]][]","[[][]][]", "[][][[]][]"]).

</lang>

Output:
<pre>
: OK
[]: OK
[][]: OK
[[][]]: OK
][: NOT OK
][][: NOT OK
[]][[]: NOT OK
[][][][][][][][][][]: OK
[[[[[[[]]]]]]]: OK
[[[[[[[]]]]]]: NOT OK
[][[]][]: OK
[[][]][]: OK
[][][[]][]: OK

: OK
[]: OK
[][]: OK
[[][]]: OK
][: NOT OK
][][: NOT OK
[]][[]: NOT OK
[][][][][][][][][][]: OK
[[[[[[[]]]]]]]: OK
[[[[[[[]]]]]]: NOT OK
[][[]][]: OK
[[][]][]: OK
[][][[]][]: OK
</pre>
</pre>