TransWikia.com

My rule does not do anything (understandably)

Mathematica Asked on November 28, 2020

I want a rule that would transform, for example, And[i,F[j,k],l,G[m,F[j,k],n],p] into And[i,F[j,k],l,G[m,T,n],p], where F, G and T are either just symbols or, say, defined by F[u_,v_]:=Or[F1[Or[Not[u],v],F2[v]] or G[x_,y_,z_]:=Or[G1[x,y],G2[z,x]] or T=H[False,True] or something even more complicated.

I have defined the following rule:

And[u___, x_, v___, y_, w___] :> And[u, x, v, y //. x -> T, w]

It never changes any expression. How should I do it properly?

3 Answers

Try this:

expr = And[i, F[j, k], l, G[m, F[j, k], n], p];
MapAt[ReplaceAll[#, F[j, k] -> T] &, expr, {4, 2}]

(*  i && F[j, k] && l && G[m, T, n] && p   *)

Have fun!

Answered by Alexei Boulbitch on November 28, 2020

ClearAll[F]
in = And[i, F[j, k], l, G[m, F[j, k], n], p]
i && F[j, k] && l && G[m, F[j, k], n] && p
in2 = And[i, F[j, k], l, G[m, F[j, k], n], Nest[H, F[1], 5] + p]
i && F[j, k] && l && G[m, F[j, k], n] && p + H[H[H[H[H[F[1]]]]]]

1. You can use Replace with level specification {2, ∞}:

Replace[in, F[__] -> T, {2, ∞}]
i && F[j, k] && l && G[m, T, n] && p
Replace[in2, F[__] -> T, {2, ∞}]
i && F[j, k] && l && G[m, T, n] && p + H[H[H[H[H[T]]]]]

2. Alternatively, use TagSetDelayed to define behavior of F inside expressions with designated heads:

ClearAll[F];
F /: (head : G | H)[a___, F[__], b___] := head[a, T, b];

in
i && F[j, k] && l && G[m, T, n] && p
in2
i && F[j, k] && l && G[m, T, n] && p + H[H[H[H[H[T]]]]]

Answered by kglr on November 28, 2020

Myself I tried something as general as possible. It would be great if somebody could optimize this, I feel it is far from perfect.

step[list_] := Module[{ul = Union[list], l, newl = {}, k, res},
  l = Length[ul];
  For[k = 1, k <= l, k++,
   AppendTo[newl, 
    ul[[k]] /. Table[ul[[j]] -> T, {j, Complement[Range[l], {k}]}]
    ]
   ];
  res = And @@ newl;
  Return[If[Head[res] === And, 
    Table[res[[k]], {k, Length[res]}], {res}]]
  ]
stab[list_] := FixedPoint[step, list]
myAnd[u___] := And @@ stab[{u}]

Answered by მამუკა ჯიბლაძე on November 28, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP