Why does the following expression not do what I expect
Array[a, 6, 0] /. a[__?MemberQ[{1, 2}, #] &] -> 0
I expect
{a{0],0,0,a[3],a{4],a[5]}
but I get
{a{0],a[1],a[2],a[3],a{4],a[5]}
What do I need to change to get what I want?
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityWhy does the following expression not do what I expect
Array[a, 6, 0] /. a[__?MemberQ[{1, 2}, #] &] -> 0
I expect
{a{0],0,0,a[3],a{4],a[5]}
but I get
{a{0],a[1],a[2],a[3],a{4],a[5]}
What do I need to change to get what I want?
You should replace __?MemberQ[{1, 2}, #] &
with __?(MemberQ[{1, 2}, #] &)
.
Because the &
has the low priority. So, the pattern is interpreted as part of the function, and not the function as part of the pattern. This can be easily seen using FullForm
:
In[24]:= __?MemberQ[{1, 2}, #] & // FullForm
Out[24]//FullForm=
Function[PatternTest[BlankSequence[], MemberQ][List[1, 2], Slot[1]]]
vs
In[25]:= __?(MemberQ[{1, 2}, #] &) // FullForm
Out[25]//FullForm=
PatternTest[BlankSequence[], Function[MemberQ[List[1, 2], Slot[1]]]]
Using the modified function, you get
Array[a, 6, 0] /. a[__?(MemberQ[{1, 2}, #] &)] -> 0
{a[0], 0, 0, a[3], a[4], a[5]}
Array[a, 6, 0] /. a[__?(MemberQ[{1, 2}, #] &)] -> 0
$\endgroup$