1
$\begingroup$

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?

$\endgroup$
  • 4
    $\begingroup$ Array[a, 6, 0] /. a[__?(MemberQ[{1, 2}, #] &)] -> 0 $\endgroup$ – ilian Jun 8 '15 at 13:44
3
$\begingroup$

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]}
$\endgroup$
  • 1
    $\begingroup$ @rcollyer, Very nice:-) Thanks a lot $\endgroup$ – xyz Jun 8 '15 at 14:02
  • 3
    $\begingroup$ This should be part of the common pitfalls for new users, but I can't seem to find it. Also, I know it is a duplicate, but finding it is difficult, at best. So, I made this as canonical of answer as I could. $\endgroup$ – rcollyer Jun 8 '15 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.