Message Boards Message Boards

0
|
7667 Views
|
1 Reply
|
2 Total Likes
View groups...
Share
Share this post:

What am I missing? Very basic

Posted 10 years ago

I've been using Mathematica for many years, and suddenly this very basic issue crops up. Why do the first and second inputs evaluate correctly but the third doesn't?

In[114]:= 

Select[{1, 2, 3, 4, 5}, # > 2 &]

Select[{1, 2, 3, 4, 5}, # > xx & /. xx -> 2]

Select[{1, 2, 3, 4, 5}, # > xx &] /. xx -> 2

Out[114]= {3, 4, 5}

Out[115]= {3, 4, 5}

Out[116]= {}
POSTED BY: Aaron S

In the case of

Select[{1, 2, 3, 4, 5}, # > xx &] /. xx -> 2

the

 Select[{1, 2, 3, 4, 5}, # > xx &]

is evaluated first (it returns {} obviously) and then the replacement rule is applied to the result (again returning {}). The standard Mathematica evaluation sequence is to evaluate expressions from the inside out of the FullForm of the expression.

FullForm[Hold[Select[{1, 2, 3, 4, 5}, # > xx &] /. xx -> 2]]

returns

Hold[ReplaceAll[
  Select[List[1, 2, 3, 4, 5], Function[Greater[Slot[1], xx]]], 
  Rule[xx, 2]]]

and this shows that the ReplaceAll in this case is the outermost function--everything inside of it is evaluated first.

In contrast your second example,

FullForm[Hold[Select[{1, 2, 3, 4, 5}, # > xx & /. xx -> 2]]]

which returns

Hold[Select[List[1,2,3,4,5],ReplaceAll[Function[Greater[Slot[1],xx]],Rule[xx,2]]]]

has the replacement rule being applied within the Select's second argument.

I hope this helps...

POSTED BY: David Reiss
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