Advertisement
sci4me

reverse associativity

Oct 27th, 2018
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 KB | None | 0 0
  1. class Leaf
  2. getter name
  3.  
  4. def initialize(@name : String)
  5. end
  6.  
  7. def to_s(io)
  8. io << "#{@name}"
  9. end
  10. end
  11.  
  12. class Op
  13. getter left
  14. getter right
  15.  
  16. def initialize(@left : Node, @right : Node)
  17. end
  18.  
  19. def to_s(io)
  20. io << "(#{@left} -> #{@right})"
  21. end
  22. end
  23.  
  24. alias Node = Op | Leaf
  25.  
  26. def to_array(a : Array(Node), node : Node)
  27. case node
  28. when Leaf
  29. a.push node
  30. when Op
  31. to_array a, node.left
  32. to_array a, node.right
  33. end
  34. end
  35.  
  36. def reverse_associativity(tree : Node)
  37. a = [] of Node
  38. to_array(a, tree)
  39.  
  40. return a.reverse.reduce { |acc, i| Op.new(i, acc) }
  41. end
  42.  
  43. a = Leaf.new "a"
  44. b = Leaf.new "b"
  45. c = Leaf.new "c"
  46. d = Leaf.new "d"
  47. e = Leaf.new "e"
  48. f = Leaf.new "f"
  49.  
  50. tree = Op.new(Op.new(Op.new(Op.new(Op.new(a, b), c), d), e), f)
  51.  
  52. puts tree
  53. puts reverse_associativity tree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement