Message Boards Message Boards

0
|
3968 Views
|
3 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Map at every term of each element of a list

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?)

3 Replies

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

POSTED BY: Neil Singer

If you don't want to write it as a lambda function (as I did), this is indeed a much better solution.

POSTED BY: Sander Huisman

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
POSTED BY: Sander Huisman
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract