Last active
January 27, 2022 15:11
-
-
Save JoelQ/abb7a45ff30f69520f8eb0b1581e6908 to your computer and use it in GitHub Desktop.
A Ruby implementation of a binary tree and its catamorphism
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 characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment