Balanced brackets: Difference between revisions

m
→‎{{header|Picat}}: Moved the approaches into subsections, added {{out}}
m (→‎{{header|Picat}}: Moved the approaches into subsections, added {{out}})
Line 5,506:
 
=={{header|Picat}}==
===Foreach loop===
Here are two approaches: one "traditional" and one using DCGs.
<lang picat> gogo1 ?=>
go1,
go_dcg,
nl.
go => true.
 
% "Traditional" approach
go1 ?=>
tests(Tests),
member(Test,Tests),
Line 5,526 ⟶ 5,519:
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
Line 5,548 ⟶ 5,527:
end,
C == 0.
 
% Using DCG
balanced --> "".
balanced --> "[", balanced, "]", balanced.
 
tests(["","[]", "[][]", "[[][]]", "][",
"][][", "[]][[]", "[][][][][][][][][][]",
"[[[[[[[]]]]]]]", "[[[[[[[]]]]]]",
"[][[]][]","[[][]][]", "[][][[]][]"]).</lang>
 
</lang>
 
{{out}}
Output:
<pre>: OK
: OK
[]: OK
[][]: OK
Line 5,574 ⟶ 5,546:
[][[]][]: OK
[[][]][]: OK
[][][[]][]: OK</pre>
 
===DCG===
: OK
Here is an implementation using DCG (Definite Clause Grammars).
[]: OK
<lang Picat>go_dcg ?=>
[][]: OK
tests(Tests),
[[][]]: OK
foreach(Test in Tests)
][: NOT OK
printf("%s: ", Test),
][][: NOT OK
if balanced(Test,[]) then
[]][[]: NOT OK
println("OK")
[][][][][][][][][][]: OK
else
[[[[[[[]]]]]]]: OK
println("NOT OK")
[[[[[[[]]]]]]: NOT OK
end
[][[]][]: OK
go1end,
[[][]][]: OK
nl.
[][][[]][]: OK
gogo_dcg => true.
</pre>
 
balanced --> "".
balanced --> "[", balanced, "]", balanced.</lang>
 
=={{header|PicoLisp}}==
495

edits