Last active
March 2, 2016 14:49
-
-
Save nsaphra/edf55e7715fa597c8493 to your computer and use it in GitHub Desktop.
Simple lisp parser for RC pair programming interview.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| type SyntaxNode | |
| label::AbstractString | |
| parent::SyntaxNode | |
| children::Array{SyntaxNode} | |
| # TODO No error handling when going up a level with undefined parent. | |
| SyntaxNode() = ( | |
| x = new(); | |
| x.label = ""; | |
| x.children = []; | |
| x.parent = x) | |
| end | |
| SyntaxNode(parent::SyntaxNode) = | |
| (x = SyntaxNode(); x.parent = parent; x) | |
| SyntaxNode(parent::SyntaxNode, label::AbstractString) = | |
| (x = SyntaxNode(parent::SyntaxNode); x.label = label; x) | |
| function addlevel!(parent::SyntaxNode) | |
| child = SyntaxNode(parent) | |
| push!(parent.children, child) | |
| return child | |
| end | |
| function addlabel!(parent::SyntaxNode, label::AbstractString) | |
| child = SyntaxNode(parent, label) | |
| push!(parent.children, child) | |
| return child | |
| end | |
| preprocess(program::AbstractString) = | |
| split( | |
| replace( | |
| replace( | |
| program, | |
| "(", " ( "), | |
| ")", " ) ")) | |
| function parselisp(program::AbstractString) | |
| unconsumed = preprocess(program) | |
| root = SyntaxNode() | |
| curr_level = root | |
| for token in unconsumed | |
| if token == "(" | |
| curr_level = addlevel!(curr_level) | |
| elseif token == ")" | |
| curr_level = curr_level.parent | |
| else | |
| addlabel!(curr_level, token) | |
| end | |
| end | |
| return root | |
| end | |
| # Added during interview. | |
| function interpretlisp(n::SyntaxNode) | |
| if length(n.label) > 0 | |
| return parse(Int, n.label) | |
| end | |
| if length(n.children) == 1 | |
| return interpretlisp(n.children[1]) | |
| end | |
| if n.children[1].label == "+" | |
| return interpretlisp(n.children[2]) + interpretlisp(n.children[3]) | |
| elseif n.children[1].label == "-" | |
| return interpretlisp(n.children[2]) - interpretlisp(n.children[3]) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment