Message Boards Message Boards

1
|
5009 Views
|
3 Replies
|
8 Total Likes
View groups...
Share
Share this post:

Why is UndirectedEdge[a, b] === UndirectedEdge[b, a] false?

Posted 8 years ago

I expected the following assertion to return a value of True but Mathematica 11 returns a value of False

UndirectedEdge[a, b] === UndirectedEdge[b, a]

If the above is "correct" to return a value of False, then my followup question is to ask what function do I apply so as to reduce a list UndirectedEdges holding what I believe to be duplicates into a minimal list of UndirectedEdge elements? e.g., what aFunction is applied so that the following would return a value of True?

aFunction[{UndirectedEdge[a, b], UndirectedEdge[b, a], UndirectedEdge[c, d], UndirectedEdge[d,c]}] === {UndirectedEdge[a, b], UndirectedEdge[c, d]}
POSTED BY: A. Chase Turner
3 Replies

You misunderstood what SameQ does. SameQ tests for structural equality. It doesn't care about the meaning of the expressions at all. If their full form looks the same, then they're the same. Otherwise not.

While adding the Orderless attribute to UndirectedEdge works in this simple test, I absolutely do not recommend modifying builtin functions like this, especially if you are a beginner. Sooner or later one of these modified functions is going to come back and bite you hard when you least expect it.

If you are certain that such a modification is the best solution, always isolate it using Block or Internal`InheritedBlock, and make sure that it has an effect only on a small piece of simple code.

 Internal`InheritedBlock[{UndirectedEdge},
   SetAttributes[UndirctedEdge, Orderless];
   <<your code here>>
 ]

For your application, I would bring the lists to a canonical form in the spirit described here:

canonical[edgeList_] := Union[Sort /@ edgeList]

Test if two edge lists are the same using canonical[edgeList1] === canonical[edgeList2].

POSTED BY: Szabolcs Horvát

This is because UndirectedEdge does not have the property Orderless:

Attributes[UndirectedEdge]

However you can add it:

SetAttributes[UndirectedEdge, Orderless]

And when you do so:

UndirectedEdge[a, b] === UndirectedEdge[b, a]

it will return True... It might affect other pieces of Mathematica as well, so be careful when changing the Attributes of built-in functions! Otherwise make your own SameQ function, that checks explicitly both permutations.

POSTED BY: Sander Huisman

Thank you -- both for the workaround and warning about possible side effects on other parts of the Mathematica system!

POSTED BY: A. Chase Turner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract