Advertisement
Guest User

Untitled

a guest
May 28th, 2015
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. # Lisp parser
  2. #
  3. # Write code that takes some Lisp code and returns an abstract syntax tree. The
  4. # AST should represent the structure of the code and the meaning of each token.
  5. # For example, if your code is given "(first (list 1 (+ 2 3) 9))", it could
  6. # return a nested array like ["first", ["list", 1, ["+", 2, 3], 9]].
  7. #
  8. # During your interview, you will pair on writing an interpreter to run the AST.
  9. class LispParser
  10.  
  11. attr_reader :tokens
  12.  
  13. def initialize(expression)
  14. @tokens = tokenize(expression)
  15. end
  16.  
  17. def read
  18. case token = pop_next_token
  19. when /\(/ then read_list
  20. when /['"].*/ then token[1..-2]
  21. when /[[:digit:]]/ then token.to_i
  22. else token.to_sym
  23. end
  24. end
  25.  
  26. private
  27.  
  28. def read_list
  29. list = []
  30. list << read until end_of_list?
  31. pop_next_token
  32. list
  33. end
  34.  
  35. def tokenize(expression)
  36. expression.gsub(/([()])/, ' \1 ').strip.split(' ')
  37. end
  38.  
  39. def peek
  40. tokens.first
  41. end
  42.  
  43. def end_of_list?
  44. peek == ')'
  45. end
  46.  
  47. def pop_next_token
  48. tokens.shift
  49. end
  50.  
  51. end
  52.  
  53. def solution(expr)
  54. lisp_expression = LispParser.new(expr)
  55. lisp_expression.read
  56. end
  57.  
  58. def assert_equal(a, b)
  59. puts a == b ? 'Passed.' : "Failed. Expected #{a} to equal #{b}"
  60. end
  61.  
  62. input = '(first (list 1 (+ 2 3) 9))'
  63. output = [:first, [:list, 1, [:+, 2, 3], 9]]
  64. assert_equal solution(input), output
  65.  
  66. input = '(first (list 1 (+ 2 3) "9"))'
  67. output = [:first, [:list, 1, [:+, 2, 3], '9']]
  68. assert_equal solution(input), output
  69.  
  70. input = '(first (list 1 (+ 2 (- 5 (\ 10 5))) 9))'
  71. output = [:first, [:list, 1, [:+, 2, [:-, 5, [:'\\', 10, 5]]], 9]]
  72. assert_equal solution(input), output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement