An unexpected behavior of PatternTest in Mathematica

后端 未结 1 2100
有刺的猬
有刺的猬 2021-02-19 20:56

I am working on toy problems to help me assimilate the idea of pattern matching in Mathematica. The following code does not behave as I expected, and I could not figure out wha

1条回答
  •  被撕碎了的回忆
    2021-02-19 21:28

    The documentation for PatternTest (aka ?) says

    In a form such as __?test every element in the sequence matched by __ must yield True when test is applied.

    Thus your code will not work as you hoped.

    A good way to see how a pattern is working is to use ReplaceList. Something close to your code is

    In[1]:= ReplaceList[{3, 4, 2, 1}, 
              {___, x__?(FromDigits[{##}] > 3 &), y___} :> {{x}, {y}}]
    
    Out[1]= {{{4}, {2, 1}}}
    

    However, if you use Condition (/;) instead of pattern test, then you can get the behaviour that you were looking for

    In[2]:= ReplaceList[{3, 4, 2, 1}, 
              {___, x__, y___} :> {{x}, {y}} /; FromDigits[{x}] > 3]
    
    Out[2]= {{{3, 4}, {2, 1}}, {{3, 4, 2}, {1}}, {{3, 4, 2, 1}, {}}, 
             {{4}, {2, 1}}, {{4, 2}, {1}}, {{4, 2, 1}, {}}, {{2, 1}, {}}}
    

    0 讨论(0)
提交回复
热议问题