Yield and recursion

Hi all,

I was just trying to grasp the concept of iterators, and
the first thing I tried was an iterator for a binary tree.

What I came up with is something like

class Node

def inorder
@left.inorder unless @left.nil?
yield @value
@right.inorder unless @right.nil?
end
end

@left, @right and @value being the obvious fields. This doesn’t
work as intended, though. (LocalJumpError IIRC).

So I tried this:

class Node

def inorder_block (block)
@left.inorder_block (block) unless @left.nil?
block.call(@value)
@right.inorder_block (block) unless @right.nil?
end

def inorder_yield 
	inorder_block { |value| yield value }
end

end

Now I can write

aNode.inorder_yield { |v| … do something with v … }

It looks to me that the second version is just an unrolled
way of writing the first one. Can anyone tell me what the difference
is?

Thanks in advance,
Christoph

  def inorder
    @left.inorder unless @left.nil?
    yield @value
    @right.inorder unless @right.nil?
  end
end

Well, ruby don't propagate automatically the block.

The first time that you call #inorder the method has the block, but then
you call it without its block. This is why ruby give an error

Guy Decoux

class Node
def inorder(&block)
@left.inorder(block) unless @left.nil?
yield @value unless block.nil?
@right.inorder(block) unless @right.nil?
end
end

– Austin Ziegler, austin@halostatue.ca on 2002.12.29 at 13.08.00

···

On Sun, 29 Dec 2002 20:56:58 +0900, Christoph Schmitz wrote:

Hi all,

I was just trying to grasp the concept of iterators, and
the first thing I tried was an iterator for a binary tree.

What I came up with is something like

I also wrote a simple BinaryTree class to help me get started with Ruby.
You can find it at
http://people.cs.uct.ac.za/~flifson/things/Ruby/Misc/BinaryTree.rb and
maybe you can get some pointers/hints from it.

Farrel

···

Data Network Architecture Research Lab mailto:flifson@cs.uct.ac.za
Dept. of Computer Science http://people.cs.uct.ac.za/~flifson
University of Cape Town +27-21-650-3127