Last active
January 27, 2022 15:11
Revisions
-
JoelQ revised this gist
Jan 27, 2022 . No changes.There are no files selected for viewing
-
JoelQ created this gist
Jan 27, 2022 .There are no files selected for viewing
This file contains 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,42 @@ class Tree attr_reader :value, :left, :right def initialize(value, left, right) @value = value @left = left @right = right end def reduce(initial, &block) left_acc = left.reduce(initial, &block) right_acc = right.reduce(initial, &block) block.call(value, left_acc, right_acc) end def inspect reduce("leaf") { |val, l, r| "#{val} (#{l}, #{r})" } end end class Leaf def reduce(initial, &block) initial end end # This section makes it easy to load up a tree in a console and experiment on it # Run the script with `ruby tree.rb` tree = Tree.new( 5, Tree.new(4, Leaf.new, Leaf.new), Tree.new( 3, Tree.new(2, Leaf.new, Leaf.new), Leaf.new ) ) binding.irb