# replacing complex numbers

I know: I'm going to make a poor showing, but really I can't understand this:

a is an expressione whose FullForm is

Power[Plus[Subscript[u,x],Times[Complex[0,-1],Subscript[u,y]],Times[Complex[0,1],Subscript[v,x]],Subscript[v,y]],2]


Why does the following code return True, instead of the expected substitution ?

b = Replace[a, {Complex[a_, b_] -> a + H b}]
a == b


I have also tried

b = Replace[a, {Complex[a_, b_] -> a + H b},levSpec]
a == b


(even Infinity included) but without succeeding.

• What exactly do you want a to look like after you've made the substitution? – Jason B. Feb 1 '16 at 13:27
• ReplaceAll[a, {Complex[0, 1] :> H, Complex[0, -1] :> -H}] – egwene sedai Feb 1 '16 at 13:30
• Try, b = Replace[a, Complex[a_, b_] :> a + H b ,Infinity] – N.J.Evans Feb 1 '16 at 13:33
• Sedai's , Jason's (see below) , and Evans's code (as far as I can understand) uses the same technique but ( perhaps, that's the very root of my failure ) I can't see why RuleDelayed is indispensable. At a first glance, there is not much left to be evaluated after the rule has been used in his direct form. Please can you give any hints ? It seems to me that the answer isn't contained in tutorial/ApplyingTransformationRules. – mitochondrial Feb 1 '16 at 14:54

The original formulation was close, and the level spec of Infinity "almost" worked. As was noted in comments, it does work if Rule is replaced by RuleDelayed. The reason it otherwise causes trouble is from a "variable capture" in scoping. The pattern variables, a_ and b_, have the same names as expressions under consideration. With Rule the rhs is evaluated immediately and the replacement becomes something unwanted. So yet another way to go about this is as below.

Clear[a, b, aa, bb]
a = Power[
Plus[Subscript[u, x], Times[Complex[0, -1], Subscript[u, y]],
Times[Complex[0, 1], Subscript[v, x]], Subscript[v, y]], 2];
b = Replace[a, {Complex[aa_, bb_] -> aa + H bb}, Infinity]

(* Out= (Subscript[u, x] - H Subscript[u, y] + H Subscript[v, x] +
Subscript[v, y])^2 *)


Moral: Be careful with pattern variable naming.

• Now I see. Evidently, I have been, instinctively and erroneously, reasoning as I was defining a function ... Thanks !! – mitochondrial Feb 1 '16 at 16:00
a = Power[
Plus[Subscript[u, x], Times[Complex[0, -1], Subscript[u, y]],
Times[Complex[0, 1], Subscript[v, x]], Subscript[v, y]], 2]

b = ComplexExpand@a /. I -> H


Assuming this is what you are going for, You can get there two ways,

Replace[a, {I x_ :> H x, -I x_ :> - H x}, Infinity]


or

a /. {I x_ :> H x, -I x_ :> - H x}

• I can't edit your post (characters). -I x_ :> -H x, you omitted sign. – thedude Feb 1 '16 at 13:50
• Thank you, dude, for abiding. (edit I want to make a Lebowski joke every time I see you on here) – Jason B. Feb 1 '16 at 13:51