Skip to content

Instantly share code, notes, and snippets.

@dharasim
Created July 31, 2019 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharasim/224917c5103ecf7958f69c3ae463e3a5 to your computer and use it in GitHub Desktop.
Save dharasim/224917c5103ecf7958f69c3ae463e3a5 to your computer and use it in GitHub Desktop.
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