guillermo
(JOSÉ GUILLERMO SÁNCHEZ LEÓN)
1
I wish to square every term of each element of a list.
Let me show the pattern (e.g.):
Map[(#^2) &, {rf[a], rf[b], rf[a] + rf[b], rf[a] + rf[b] + rf[c]}, {2}]
I obtain as output:
Out:= {rf(a^2), rf(b^2), rf(a)^2+rf(b)^2, rf(a)^2+rf(b)^2+rf(c)^2}
But I want to obtain:
Out:= {rf(a)^2, rf(b)^2, rf(a)^2+rf(b)^2, rf(a)^2+rf(b)^2+rf(c)^2}
I realize that it happens when the element of list has only one term, then level 2 is applied inside this term, but how can I avoid it?)
sghuisman
(Sander Huisman)
2
The easiest might be to do something like this (with your original list being i):
sq = # # &;
Map[If[Head[#] === Plus, Map[sq][#], sq[#]] &, i]
Or actually:
i /. (x : rf[_]) :> x^2
neils
(Neil Singer)
3
Guillermo,
@Sander Huisman has a great solution. Another alternative that works on any expression (not just ra[]).
mysq[x_Plus] := Map[mysq, x]
mysq[x_] := x^2
SetAttributes[mysq, Listable]
In[13]:= i = {a, b + c + d, c};
mysq[i]
Out[14]= {a^2, b^2 + c^2 + d^2, c^2}
Regards,
Neil
sghuisman
(Sander Huisman)
4
If you don’t want to write it as a lambda function (as I did), this is indeed a much better solution.