Skip to content

Commit ab901ce

Browse files
committed
ENH #52 Implemented parentheses checker.
1 parent 8e78334 commit ab901ce

File tree

4 files changed

+35
-0
lines changed

4 files changed

+35
-0
lines changed

src/Q.jl

+1
Original file line numberDiff line numberDiff line change
@@ -108,5 +108,6 @@ if GOT_Q
108108
else
109109
include("client.jl")
110110
end
111+
include("parser.jl")
111112
end # module Q
112113
include("q-prompt.jl")

src/parser.jl

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
balanced(parens) -> checker
3+
4+
The `checker` function returns position of misbalanced parenthesis
5+
or 0 is the given string is balanced, and -1 if there are more open
6+
parentheses than closed.
7+
"""
8+
function balanced(parens="()[]{}")
9+
openers = parens[1:2:end]
10+
closers = parens[2:2:end]
11+
action = Dict(o => (o, +1) for o in openers)
12+
merge!(action, Dict(c => (o, -1) for (o, c) in zip(openers, closers)))
13+
init = Dict(zip(openers, zeros(Int, length(openers))))
14+
function(cmd::AbstractString)
15+
state = copy(init)
16+
for (i, x) in enumerate(cmd)
17+
x, n = get(action, x, ('x', 0))
18+
if x != 'x' && (state[x] += n) < 0
19+
return i
20+
end
21+
end
22+
any(x > 0 for x in values(state)) ? -1 : 0
23+
end
24+
end
25+
const chkparens = balanced()

test/parser-tests.jl

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import Q: chkparens
2+
@testset "parser" for (n, cmd) in [
3+
(0, "([{}])"),
4+
(-1, "([{}]"),
5+
(5, "((([}])))"),
6+
]
7+
@test n == chkparens(cmd)
8+
end

test/runtests.jl

+1
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,6 @@ const side = GOT_Q ? "server" : "client"
1616
include("text-tests.jl")
1717
include("list-tests.jl")
1818
include("table-tests.jl")
19+
include("parser-tests.jl")
1920
include("$side-tests.jl")
2021
end

0 commit comments

Comments
 (0)