From: Christopher Dicely Date: 2011-05-03T16:57:49+09:00 Subject: Re: Help making a method more concise On Tue, May 3, 2011 at 12:30 AM, Robert Klemme wrote: > On Tue, May 3, 2011 at 6:28 AM, Christopher Dicely wrote: >> On Mon, May 2, 2011 at 11:17 AM, Mark Hayes wrote: >>> Hello, >>> >>> I'm looking to improve my skills as a Rubyist and would like to know if the >>> "depth" method could be expressed more precisely.  Any help would be greatly >>> appreciated, thanks! >>> >>> require 'test/unit' >>> >>> class Node >>>  attr_accessor :value, :lchild, :rchild >>> >>>  def depth >>>    [lchild ? lchild.depth : 0, rchild ? rchild.depth : 0].max + 1 >>>  end >>> end >> >> >> def depth >>  1 + [lchild,rchild].map {|ch| [ch}.max >> end > > Does not work: apart from the syntax invocation of #depth is missing. > If we add that we have a solution that has been proposed already. Uh, yeah. I messed something up in editing that. I'm not entirely sure what it was supposed to be. > >> or even: >> >> def depth >>   1 + [lchild,rchild].map(&:to_i).max >> end >> >> alias to_i depth > > Now that's an interesting idea to use the knowledge that nil.to_i => 0! > >> or: >> >> add empty (no value) left & right children when you first add a value >> to a node, and: >> >> def empty? >>  @value.nil? >> end >> >> def depth >>  empty? ? 0 : [lchild,rchild].map(&:depth).max >> end > > I don't think this captures the original semantics properly.  Now > there are only two states: empty, not empty.  But the original design > allowed for more states: empty, left set, right set, both set.  Even > if not for #depth this is likely important for other tree algorithms. Yeah, it depends on things in the code we can't see; most of the tree implementations I've seen either use nil pointers for children and populate them with real nodes when they get data for them, or use empty nodes for children only of populated nodes and then populate the empty nodes when data arrives for them, but its possible that this one needs more differentiation.