14
$\begingroup$

I want to turn a sum like this

sum =a-b+c+d

Into a List like this:

sumToList[sum]={a,-b,c,d}

How can I achieve this?

$\endgroup$
  • 2
    $\begingroup$ I am a professor of "vectorial analysis" in Mexico. I try to teach the subjects with the use of "Mathematica". I solved a problem seeing this page and also this: mathematica.stackexchange.com/questions/100758/… ... in which I was not allowed to comment. This was what I did to find the "scalar potential function". i.stack.imgur.com/ugIlP.png $\endgroup$ – David Gardea Feb 6 '17 at 17:43
  • $\begingroup$ @David I converted your answer to a comment, as it seems more appropriate as such. I know that new users do not have the "privilege" to comment everywhere (a "spam" control measure I believe) but if you continue to participate you will find that you soon do. $\endgroup$ – Mr.Wizard Feb 6 '17 at 19:12
18
$\begingroup$
List @@ sum

{a, -b, c, d}

From the docs on Apply (@@):

f@@expr replaces the head of expr by f.

So List@@sum replaces Head[sum] (that is, Plus) with List.

You can also get the same result by changing 0th Part of sum (which is its Head) to List:

sum[[0]] = List; sum

{a, -b, c, d}

$\endgroup$
  • $\begingroup$ There is a slight hiccup that you can encounter using this. If you're not explicitly doing a sum, you will list over whatever the head of the function is. e.g. List @@ 2*3 will result in {2,3} $\endgroup$ – Alex DB Feb 10 '17 at 17:10
  • $\begingroup$ @AlexDB, you are right; List@@expr does change the head of expr, whatever it is, to List. $\endgroup$ – kglr Feb 10 '17 at 17:16
9
$\begingroup$

Try :

a - b + c + d /. Plus -> List

You can have a look at a - b + c + d //FullForm to see why this works.

$\endgroup$
  • 3
    $\begingroup$ Good one. And maybe sum[[0]] = List; sum $\endgroup$ – user1066 Oct 22 '12 at 19:32
  • 1
    $\begingroup$ @TomD that is the one I like to use :) $\endgroup$ – Mike Honeychurch Oct 22 '12 at 22:24
5
$\begingroup$

Still another route:

Last[CoefficientArrays[#]] Variables[#] &[a - b + c + d]
   {a, -b, c, d}
$\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.