Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Using parser combinators in Julia https://github.com/wdebeaum/PEG.jl
module TreeFromString
using PEG
import Base: show
struct Tree{T}
val ::T
children ::Vector{Tree{T}}
end
isterminal(t::Tree) = isempty(t.children)
function show(io::IO, t::Tree)
if isterminal(t)
print(io, t.val, ' ')
else
print(io, "[.", t.val, ' ')
foreach(t -> print(io, t), t.children)
print(io, ']')
end
end
@rule token = r"[^\[\] ]*" & " " >
(terminal, space) -> Tree{String}(terminal, String[])
@rule nonterminal = "[." & r"[^\[\] ]*" & " " & tree[+] & "]" >
(open, nonterminal, space, children, close) -> Tree{String}(nonterminal, children)
@rule tree = nonterminal, token
let str = "[.C [.D1 D2 ] E ]"
@assert string(tree(str)[1]) == str
end
end # module
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment