Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Leaf
- getter name
- def initialize(@name : String)
- end
- def to_s(io)
- io << "#{@name}"
- end
- end
- class Op
- getter left
- getter right
- def initialize(@left : Node, @right : Node)
- end
- def to_s(io)
- io << "(#{@left} -> #{@right})"
- end
- end
- alias Node = Op | Leaf
- def to_array(a : Array(Node), node : Node)
- case node
- when Leaf
- a.push node
- when Op
- to_array a, node.left
- to_array a, node.right
- end
- end
- def reverse_associativity(tree : Node)
- a = [] of Node
- to_array(a, tree)
- return a.reverse.reduce { |acc, i| Op.new(i, acc) }
- end
- a = Leaf.new "a"
- b = Leaf.new "b"
- c = Leaf.new "c"
- d = Leaf.new "d"
- e = Leaf.new "e"
- f = Leaf.new "f"
- tree = Op.new(Op.new(Op.new(Op.new(Op.new(a, b), c), d), e), f)
- puts tree
- puts reverse_associativity tree
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement