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:

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

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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.