# Overriding TwoWayRule for in-place element swapping

I'd like to make \[TwoWayRule] work for things other than graph edges, for example, for swapping i.e. Replace, ReplaceAll, StringReplace, etc:

{1,2,3} /. 1 <-> 2
StringReplace["a b c", "a" <-> "b"]


Unfortunately, Replace and friends are kernel functions, and I don't want to break anything accidentally. Any suggestions?

I don't think this will break anything:

Unprotect[TwoWayRule];
TwoWayRule /: ReplaceAll[a_, TwoWayRule[x_, y_]] :=
ReplaceAll[a, {x -> y, y -> x}]
Protect@TwoWayRule


Here you are adding an UpValue to TwoWayRule which is much safer than adding a DownValue to ReplaceAll.

{1, 2, 3} /. 1 <-> 2
(* {2, 1, 3} *)


Note that this is a very limited definition, it won't cover cases where you have a list of replacement rules.