Is there a function that replaces the first occurence of the expression instead of replacing all? For example, if I have HoldForm[x + 2 + 4 + x] /. x -> 4, is there a way to return 4 + 2 + 4 + x?
4 Answers
$\begingroup$ $\endgroup$
Another way:
hf = HoldForm[x + 2 + 4 + x] i = 0 hf /. (x :> 4 /; i++ == 0) 4 + 2 + 4 + x
$\begingroup$ $\endgroup$
4 Well here's a way. Find the position of the first occurrence of x:
expr = HoldForm[x + 2 + 4 + x]; pos = Position[expr, x, -1, 1]; Then:
ReplacePart[expr, pos -> 4] 4 + 2 + 4 + x
- 6$\begingroup$ +1 With version 10, we can use
FirstPosition, e.g.HoldForm[x + 2 + 4 + x] // ReplacePart[#, FirstPosition[#, x] -> 4] &. $\endgroup$WReach– WReach2014-09-24 05:22:29 +00:00Commented Sep 24, 2014 at 5:22 - $\begingroup$ @WReach I was just updating the answer with that optimization. I considered using
FirstPositionbut it doesn't seem to bring much benefit here (a bit of clarity I guess) so I used the general equivalent. $\endgroup$Mr.Wizard– Mr.Wizard2014-09-24 05:24:15 +00:00Commented Sep 24, 2014 at 5:24 - $\begingroup$ @Mr.Wizard, thanks for the update, certainly cleaner :) $\endgroup$RunnyKine– RunnyKine2014-09-24 05:38:57 +00:00Commented Sep 24, 2014 at 5:38
- $\begingroup$ @WReach, good point, I forgot about
FirstPosition$\endgroup$RunnyKine– RunnyKine2014-09-24 05:39:49 +00:00Commented Sep 24, 2014 at 5:39
$\begingroup$
$\endgroup$
4 Edit
For order preserving as Jens says, I changed Attributes
ClearAttributes[Plus, Orderless] HoldForm[7 + x + 2 + 4 + x + 5] /. f___ + x + l___ :> f + 4 + l 7 + 4 + 2 + 4 + x + 5
And you can revert by SetAttributes[Plus, Orderless]
Origin
How about this
HoldForm[x + 2 + 4 + x] /. x + a___ -> 4 + a 4 + 2 + 4 + x
- $\begingroup$ It won't work with this example:
HoldForm[7 + x + 2 + 4 + x] /. x + a___ -> 4 + abecause the order isn't preserved. $\endgroup$Jens– Jens2014-09-24 02:25:48 +00:00Commented Sep 24, 2014 at 2:25 - $\begingroup$ @Jens : I got it, and I changed attributes. $\endgroup$Junho Lee– Junho Lee2014-09-24 04:37:33 +00:00Commented Sep 24, 2014 at 4:37
- $\begingroup$ Yes, that works. But now you'd have to do the same if it were
Timesinstead ofPlus... anyway, you put your finger exactly on the reason why the original didn't work, and changing the attributes is certainly a way to make it work. $\endgroup$Jens– Jens2014-09-24 05:21:53 +00:00Commented Sep 24, 2014 at 5:21 -
$\begingroup$ $\endgroup$
expr = HoldForm[x + 2 + 4 + x]; expr[[##& @@ FirstPosition[expr, x]]] = 4; expr 4 + 2 + 4 + x
x? $\endgroup$ClearAll[r]; r[4] := (r[4] = x; 4); HoldForm[x + 2 + 4 + x] /. x :> RuleCondition@r[4]and for less fun take a look atPosition4th arg +ReplacePart. $\endgroup$