Skip to content

Instantly share code, notes, and snippets.

@JoelQ
Last active January 27, 2022 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoelQ/abb7a45ff30f69520f8eb0b1581e6908 to your computer and use it in GitHub Desktop.
Save JoelQ/abb7a45ff30f69520f8eb0b1581e6908 to your computer and use it in GitHub Desktop.
A Ruby implementation of a binary tree and its catamorphism
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