What are recursive arrays good for?

2019-01-11 02:50发布

问题:

Ruby supports recursive arrays (that is, self-containing arrays):

a = []
# => [] 
a << a
# => [[...]] 
a.first == a
# => true 

This is intrinsically cool, but what work can you do with it?

回答1:

A directed graph with undifferentiated edges could have each vertex represented simply as an array of the the vertices reachable from that vertex. If the graph had cycles, you would have a 'recursive array', especially if an edge could lead back to the same vertex.

For example, this graph:

...could be represented in code as:

nodes = { a:[], b:[], c:[], d:[] }
nodes[:a] << nodes[:a]
nodes[:a] << nodes[:b]
nodes[:b] << nodes[:a]
nodes[:b] << nodes[:c]
p nodes
#=> {:a=>[[[...], []], [...]], :b=>[[[...], [...]], []], :c=>[], :d=>[]}

Usually the representation of each vertex would be more 'robust' (e.g. a class instance with properties for the name and array of outgoing edges), but it's not impossible to imagine a case where you wanted a very lightweight representation of your data (for very large graphs) and so needed to use a minimal representation like this.



回答2:

Ruby supports recursive arrays

To me the question is why should it not support it?

An Array is simply a collection of references. Should it check each element and throw an error if one of the refers to the collection itself, so prevent recursion or using it for graphs like Phrogz' example.

So I don't think it's a feature, but if it would be, most languages I know has it, even Java.. Just use Object as Array elements.