From: Jim Weirich Date: 2005-07-29T00:49:16+09:00 Subject: Re: What's so special about operators, built-in classes and modules? Ara.T.Howard said: > On Thu, 28 Jul 2005, Daniel Brockman wrote: > >> As has been pointed out countless times already, the diamond inheritance >> problem already exists in Ruby: >> >> module A >> def initialize(val) >> @var = val >> end >> end >> >> module B >> include A >> def initialize >> super(5) >> end >> end >> >> module C >> include A >> def initialize >> super(42) >> end >> end >> >> class D >> include B >> include C >> end > > > did you run this? this is most defintely __not__ the diamond problem - it > is strictly a tree: From my point of view, it looks like a diamond include structure, i.e. A / \ B C \ / D Ruby does linearizes the method resolution order to D,C,B,A. > if this were the diamond problem ruby would have needed to choose between > __either__ the 'initialize' in B or C but, Correct, and it chooses C (which in turn calls B because of the super in C). > because we are walking a tree, > it simply does both - each 'include' statement is adding depth to > the search but it never becomes a complex graph that needs an > algorithim which resolves conflicts. Actually, there *is* an algorithm that reduces the graph to a simple linear search. As modules are included, the included module's search order is appended to the beginning of the new search order, minus any modules that are already included. In fact, Ruby's MRO algorithm for modules is very similar to Python's (old[1]) MRO for multiple inheritance (except Ruby favors the last module added last and Python favors the first class added). > see > > http://en.wikipedia.org/wiki/Diamond_problem I found this particular entry to be less helpful than other resources. The problem is rarely which method to call (which actually is not a diamond inheritance problem ... it can arise whenever two base classes share a method with a common name). The big problem with diamond inheritance is the question of instance data ... do you have one or two copies? (and given the way Ruby handles instance variables, I find it hard to imagine the answer to this question would ever be two). > for more on this. again - there no ambiguity in which 'initialize' ruby > calls (both) and therefore no diamond problem. -- -- Jim Weirich jim@weirichhouse.org http://onestepback.org ----------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas) [1] I understand that modern Python supports a different algorithm than the one described on the wikipedia page. See http://www.python.org/2.3/mro.html for details.