Message Boards Message Boards

0
|
2569 Views
|
5 Replies
|
4 Total Likes
View groups...
Share
Share this post:

Differences in the results of the Map command (/@)

Posted 3 years ago
In[1]:= Map[Function[x, x^2], a + b + c]

Out[1]= a^2 + b^2 + c^2

In[2]:= Function[x, x^2] /@ a + b + c

Out[2]= a + b + c

I expect Out[1] and Out[2] to be the same....which is not

In[3]:= Map[Function[x, x^2], {a + b + c}]

Out[3]= {(a + b + c)^2}

In[4]:= Function[x, x^2] /@ {a + b + c}

Out[4]= {(a + b + c)^2}

Now Out[3] and Out[4] are the same, as expected.

What's the difference between the two cases? Thank you very much for a kind reply

POSTED BY: andrea andrea
5 Replies
Posted 3 years ago

Yes..it is important to deeply understand all caveats of a command before applying it.

For example you can have Map apply also to level 0 using Map[f,expr,{0}]....but try Map[f,expr,0] and look at the difference

POSTED BY: andrea andrea

The symbol a has nothing at level 1. This

(Function[x, x^2] /@ a)

tries to map a function to a level that does not exist. The designers decided that this mapping just does nothing and keeps silent. It might have given an error message or at least a warning.

POSTED BY: Gianluca Gorni
Posted 3 years ago

Sorry Gianluca it is clear now to me your answer.

Mapping the function at level 1 on just a (because of precedente the result is a.....which the is summed to b+c

Thanks again

POSTED BY: andrea andrea
Posted 3 years ago

Thanks Gianluca...it seems actually related to the levels of the expression the Map function is applied to. By default Map[f,expr] is equivalent to Map[f,expr,{1}]. which explains Map[f,a+b,{1}] = a^+b^2.

Try with

Table[Map[Function[x, x^2], a + b, {n}], {n, 0, 1}] and see the result

However it is not clear why /@ does not get the same result (it seems applied to an higher level of the expression a+b)

POSTED BY: andrea andrea

It is because of the precedence of operations.

Function[x, x^2] /@ a + b + c

is interpreted ad

(Function[x, x^2] /@ a) + b + c
POSTED BY: Gianluca Gorni
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