How do I create an iterator over a recursive data structure in Crystal?

144 Views Asked by At

I have a tree structure and currently I am trying to return an iterator that iterates over the elements of the datastructure so that my function can accept a block.

I have currently reduced my code to this:

# tree.cr
class Tree
  property children : Array(Tree)

  def initialize(@value : Int32)
    @children = [] of Tree
  end

  def add(child : Tree)
    @children << child
  end

  def each_leaf : Iterator(Int32)
    Iterator.chain [{@value}.each, @children.each.flat_map(&.each_leaf)]
  end
end

root = Tree.new 3
root.add Tree.new 1
root.add Tree.new 5

p root.each_leaf.to_a # no output from here
p "hi" # no output from here either

Interestingly the code snippet above simply terminates, and the second print p "hi" doesn't get executed either. Would love to hear pointers on how this code could be corrected. Thanks in advance.

Edit: Here are some details of the executing environment

  • Crystal Version: v1.7.2
  • Command: crystal run tree.cr
  • Output: Program received and didn't handle signal TRAP (5)
  • System: M1 Macbook Pro, Monterey 12.6
0

There are 0 best solutions below