3
$\begingroup$

So in my notebook I have a list of long expressions which are sums of a bunch of terms. I would like to look at each of these terms individually and try to remove them based on some criteria. My idea was to replace the head of the first Plus with List, and then look at the individual terms from there as they would be separated into a list. I want to use Replace instead of ReplaceAll because on lower levels there may be sums inside exponentials that I don't want to replace. A toy illustration of what I'm doing now (which doesn't work) is something like this:

Replace[{x+y},Plus -> List, 1]

In my mind this should work, but it doesn't seem to. ReplaceAll works ok

ReplaceAll[{x+y},Plus -> List]

but I don't think this is really what I want. Any help would be greatly appreciated, or even a different way of approaching the problem would be great too!

$\endgroup$
  • 1
    $\begingroup$ Even if Replace worked that way, the third argument should have been {2}. Plus is at level 2 because you need two numbers to obtain it with part {x+y}[[1,0]] $\endgroup$ – Coolwater Feb 2 '17 at 19:12
  • 1
    $\begingroup$ You could write MapAt[List&, expr, Position[expr, Plus, {2}]] $\endgroup$ – Coolwater Feb 2 '17 at 19:14
  • 2
    $\begingroup$ Applywith a level specification may be what you need : Apply[List,{x+y},{1}] $\endgroup$ – andre314 Feb 2 '17 at 19:57
10
$\begingroup$

You need the option Heads -> True. The default behavior of Replace is to ignore heads like Plus.

Replace[{x + y}, Plus -> foo, {2}, Heads -> True]

{foo[x, y]}

$\endgroup$
  • $\begingroup$ Thank you very much! This works perfectly $\endgroup$ – swalsh1123 Feb 3 '17 at 11:19

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.