5
$\begingroup$

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?

$\endgroup$
4
$\begingroup$

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.

$\endgroup$

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.