nitlang / nit

Nit language
http://nitlanguage.org
Apache License 2.0
239 stars 65 forks source link

digraph: Implementation of a reflexive directed graph #2784

Closed Delja closed 5 years ago

Delja commented 5 years ago

Add the implementation of a reflexive directed graph. Added element is in relation with itself (ie if the graph has u node is implies self.has_arc(u,u) == true)

Delja commented 5 years ago
var reflexive_digraph = new ReflexiveHashDigraph[Int]
reflexive_digraph.add_vertex(1)
assert reflexive_digraph.has_arc(1,1)

var digraph = new HashDigraph[Int]
digraph.add_vertex(1)
digraph.add_arc(1,1) # The line is needed if your want to `1` has_arc on itself
assert digraph.has_arc(1,1)

Here is a comparison between the two classes of graphs. Both have the same goal, the reason of ReflexiveHashDigraph it's just to remove the add_arc step.

@Morriar The motivation is simply to remove a potential mistake when you need all vertices to be reflexive. The other way would be to add a method in HashDigraph to make all the vertices reflexive, but for me it's a better solution to add a specific class to do that.

Morriar commented 5 years ago

@Delja what about adding an option to the current HashDigraph?

var digraph = new HashDigraph[Int](all_nodes_reflexive = true)
digraph.add_vertex(1)
assert digraph.has_arc(1,1)
privat commented 5 years ago

@Morriar I'm not sure an option is simpler. I suspect it will add a lot of if in the code and an additional fragility is the flag is toggled during the life of the object. Another approach could be a decorator design pattern. It is cleaner but more complex and maybe overkill.

I'm OK with a subclass. It is not perfect but the other design do not seem that better for the current usage.