问题描述
我正在研究玩具问题,以帮助我理解 Mathematica 中模式匹配的想法.以下代码的行为不符合我的预期,我无法弄清楚我对 PatternTest 的理解有什么问题.
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 what is wrong with my understanding of PatternTest.
MatchQ[{2, 1, 2, 5}, {x__?(FromDigits[{#}] > 3 &), y__}]
我希望这段代码可以检查列表 {2,1,2,5}
是否可以写成两个连续的(非空)序列,以便我们从第一个序列大于 3.由于 {Sequence[2,1],Sequence[2,5]}
是重写列表的一种方法,使得 FromDigits[{2,1}]>3
成立,我希望该代码返回值 True
.然而,事实并非如此.
I expected this piece of code to check if the list {2,1,2,5}
can be written as two consecutive (non-empty) sequences such that the integer we get from the first sequence is greater than 3. Since {Sequence[2,1],Sequence[2,5]}
is one way to rewrite the list such that FromDigits[{2,1}] > 3
holds, I expected that code to return the value True
. However, that is not the case.
我对代码的解释有什么问题?
What is wrong with my interpretation of the code?
推荐答案
PatternTest 的文档(又名 ?
)说
在__?test
这样的形式中,序列中的每个元素都与__
匹配应用测试时必须产生 True
.
因此您的代码将无法如您所愿.
Thus your code will not work as you hoped.
查看模式如何工作的一个好方法是使用 ReplaceList
.与您的代码接近的东西是
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}, {}}}
这篇关于Mathematica 中 PatternTest 的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!