Last active
December 23, 2017 18:35
-
-
Save robertothais/dac7557935b5daa42cc8131fbcf6d91e to your computer and use it in GitHub Desktop.
Pairing Interview Submission for RC
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
| class Lisp | |
| def initialize(program) | |
| @program = program | |
| end | |
| def tokenize | |
| matches = { | |
| parens: '[()]', | |
| string: '".*?(?<!\\\)"', | |
| atom: '\S+?(?:(?=[()])|(?=\s)|(?=$))' | |
| } | |
| pattern = Regexp.new(matches.values.join('|')) | |
| @program.scan(pattern) | |
| end | |
| def parse | |
| tokens = tokenize | |
| ast = parse_list(tokens) | |
| raise SyntaxError if tokens.any? | |
| ast | |
| end | |
| def parse_list(tokens) | |
| raise SyntaxError unless tokens.shift == '(' | |
| list = [] | |
| while tokens[0] != ')' | |
| raise SyntaxError if tokens.empty? | |
| if tokens[0] == '(' | |
| list << parse_list(tokens) | |
| else | |
| list << parse_atom(tokens.shift) | |
| end | |
| end | |
| tokens.shift | |
| list | |
| end | |
| def parse_atom(atom) | |
| return Integer(atom) rescue | |
| return Float(atom) rescue | |
| atom | |
| end | |
| end | |
| puts Lisp.new(ARGF.read).parse.inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment