Skip to main content

Questions tagged [pattern-matching]

Questions on expression testing and manipulation through pattern matching and constructing efficient patterns.

118 questions with no upvoted or accepted answers
Filter by
Sorted by
Tagged with
23 votes
0 answers
342 views

What has changed in pattern matching functions with the Orderless attribute?

Bug introduced in 10.1 and fixed in 11.0(.1) In making an attempt to answer this question, we ran into a version-dependent pattern-matching issue. An extended discussion in the comments transpired, ...
march's user avatar
  • 23.9k
14 votes
0 answers
180 views

Alternatives and the Flat attribute

When a head has the attribute Flat then the pattern matcher is able to pick out a sublist of its arguments, even though the structure doesn't match: ...
Martin Ender's user avatar
  • 8,774
13 votes
0 answers
153 views

Orderless breaks pattern match

Bug introduced in 10.3 or earlier and persisting through 12.0.0 10.0.2 is not affected. I am perplexed by the effect of Orderless on pattern matching. Starting ...
Kvothe's user avatar
  • 4,591
10 votes
0 answers
217 views

PatternSequence, Optional and _Symbol

Bug introduced in 9.0 or earlier, partially fixed in 10.1 and persisting through 11.3 [CASE: 4075992] confirmed Note: See (72290) for the fixed part of the bug. Consider the following example: <...
Lukas Lang's user avatar
  • 34.2k
9 votes
0 answers
169 views

Strange result of DeleteCases in an association

Bug introduced in 10.1.0 and fixed in 10.3.1 The function DeleteCases can be used for associations, also with level specification. Here is an example where some ...
Fred Simons's user avatar
  • 10.2k
8 votes
1 answer
214 views

Can you explain this substitution rule?

This rule behaves as I expect: b . c + a . b . c /. (b . c) -> x (* x + a . x *) I would expect the same result with this: ...
mikado's user avatar
  • 16.8k
8 votes
0 answers
74 views

Why does Longest not work on OptionsPattern?

When having a function with optional arguments and options, I frequently find myself writing something like this: ...
Lukas Lang's user avatar
  • 34.2k
8 votes
0 answers
163 views

KeyValuePattern specificity in DownValues

Bug introduced in 10.4.0 and persisting through 11.3.0 CASE:3824590 [...] Developers are discussing this behavior. [...] I will let you know when I have definite information on this. [...] ...
Kuba's user avatar
  • 137k
8 votes
0 answers
322 views

Convert logical relational expression to / from disjunctive and conjunctive forms?

I would like to convert logical relational expressions in disjunctive form, e.g., $$(x \lt -1) \lor (-1 \lt x \lt +1) \lor (x \gt +1)$$ into conjunctive form, e.g., $$(x \ne -1) \land (x \ne +1)$$ ...
RandomBits's user avatar
7 votes
0 answers
166 views

Exceeding recursion limit with no obvious recursion: Optional pattern-matching causing nonlocal behavior

So, I've come across something strange, and wanted to get a deeper understanding of what was going on. Consider the following code: ...
thorimur's user avatar
  • 9,020
6 votes
0 answers
95 views

Using Cases to select expressions from a list

I am using v12.2.0 on Win7-x64. I want to use Cases to select the Times and Plus cases from ...
Syed's user avatar
  • 55.7k
6 votes
0 answers
119 views

Difference between the infinite rewriting behavior of evaluation and ReplaceRepeated

In the documentation tutorial/Evaluation it's said that: Every time the expression changes, the Wolfram Language effectively starts the evaluation sequence over ...
asd1dsa's user avatar
  • 573
6 votes
0 answers
114 views

Examples of the single dot form of Optional?

I've known of the single dot form of Optional for a while, but never had occasion to actually use it: Are there any good examples of use cases for it other than in relation to ...
M.R.'s user avatar
  • 31.6k
5 votes
0 answers
64 views

How to use Shortest[___] with Sequence pattern matching?

Shortest[] doesn't appear to work with Sequence s. Is this a bug or a feature? What can I do to force the following ...
podge cassidy's user avatar
5 votes
0 answers
59 views

Why does MatchQ[Hold[c + b + a], Hold[x_ + b + a]] return False?

Can anyone explain why the following pattern matches: [In1]:MatchQ[Hold[a + c + b], Hold[x_ + b + a]] [Out1]:True But this one fails: ...
user61796's user avatar
5 votes
0 answers
82 views

Can't seem to match multiple KeyValuePatterns in one pattern

Let's define a couple patterns that we can use to match Associations. ...
Pillsy's user avatar
  • 18.5k
5 votes
0 answers
103 views

Why does Shortest not work inside SequencePosition?

Why does Shortest not work in a SequencePosition call? The following two commands return the same answer: ...
Roman's user avatar
  • 48.3k
5 votes
0 answers
63 views

How to match -1 at arbitrary precision?

Suppose a want a pattern to match: -1 -1. -1.`42 (or any other value for the precision) with a pattern. What would be the best pattern to use? I guess one could ...
TimRias's user avatar
  • 3,180
5 votes
0 answers
115 views

Pattern match Shortest BlankNullSequence in SequencePosition

Apologies if this has an answer somewhere but I can't find it. From the examples for SequencePosition we are shown that ...
Quantum_Oli's user avatar
  • 7,974
5 votes
0 answers
396 views

Syntax error for optional pattern, but only in debugger

This expression (explained here by Leonid) evaluates fine unless Evaluation->Debugger is enabled: h[x : (_Integer) : 1] := x Syntax::sntxf: "x:" cannot be ...
ssch's user avatar
  • 16.6k
4 votes
0 answers
77 views

Condition-in-scope as a rule for SequenceReplace

Bug persisting through 13.1.0 [CASE:4841653] From ...
rnotlnglgq's user avatar
  • 3,740
4 votes
0 answers
77 views

Preventing $-renaming of pattern names in lexically-scoped constructs

When you use a lexically-scoped construct like With or Function to perform replacements in an expression, Mathematica might ...
thorimur's user avatar
  • 9,020
4 votes
0 answers
123 views

`Optional` with non-empty list requires PatternTest/Condition?

Arbitrary lists are easy to use with Optional: a[0]~MatchQ~a[0, Optional[x_List, {}]] a[0]~MatchQ~a[0, Optional[x:{___}, {}]] ...
masterxilo's user avatar
  • 5,739
4 votes
0 answers
76 views

How to get f[x] to match with f[c_., x] when OneIdentity doesn't match

After setting: SetAttributes[f, OneIdentity] Default[f] = 1; We have the following successful matches: ...
QuantumDot's user avatar
  • 19.7k
4 votes
0 answers
135 views

Why the flat f[x] is treated as ghostHead_[f[x]]?

While reading this answer I feel confused. If we do not care any specific detail of the original question, then ybeltukov's answer essentially makes use of the following fact ...
saturasl's user avatar
  • 1,429
3 votes
0 answers
79 views

Association vs Pattern Matching: which one is better for data storage?

Say I have a few key-value pairs. I can store them with Association as ...
atbug's user avatar
  • 685
3 votes
0 answers
76 views

What's the time / space complexity of pattern matching?

For example, in ReplaceAll[expression, pattern], what are the main algorithms used internally? How does the asymptotic time / space complexity scale with the length ...
felix's user avatar
  • 549
3 votes
0 answers
121 views

Select certain term containing some patterns and confusing pattern Alternatives in FreeQ

I am considering a function termsContain[func_,list_] which select in an expression func the terms containing the ones in the ...
XiaoaiX's user avatar
  • 397
3 votes
0 answers
200 views

Fast way to check if an expression matches any of the rules in a list?

I have a function defined roughly like so. This is a minimum recreation. foo[expr_, rules: {__Rule}] := "some fancy result" /; AnyRuleMatchesQ[expr, rules]; What ...
Mosaic Blounder's user avatar
3 votes
0 answers
99 views

Match Polish letters

I am quite confused about the following cases, in Mathematica 9.0.1.0: LetterQ["ł"] StringMatchQ["ł", WordCharacter ..] The first case gives <...
Per Alexandersson's user avatar
3 votes
0 answers
477 views

Generating a list of random numbers that follows a pattern

I'm a beginner to Mathematica. I'm writing a code to design a 4-bar linkage mechanism that traces a path in 2D space. I got the modelling done right, now I'm writing my own implementation of a genetic ...
Mahmoud Mousa's user avatar
3 votes
0 answers
114 views

Is pattern matching just systematic guessing and checking?

How does the pattern matcher work? how does it match this example? f[3, h[4]] /. f[x_, z_[y_]] :> {x, y, z} My guess is that the pattern matcher collects all ...
Conor Cosnett's user avatar
3 votes
0 answers
248 views

I am missing a function like HoldPattern

Temporary message: I am planning to edit this question, making the examples less confusing and by moving the things that are confusing to a separate question For any confusion about expressions that ...
Jacob Akkerboom's user avatar
2 votes
0 answers
72 views

DigitQ, LetterQ, UpperCaseQ, LowerCaseQ on empty string

Is this a bug or I am missing something? #[""] & /@ {DigitQ, LetterQ, UpperCaseQ, LowerCaseQ} ...
azerbajdzan's user avatar
  • 19.7k
2 votes
0 answers
44 views

Assign a name for OrderlessPatternSequence

...
Crack-Hu's user avatar
2 votes
0 answers
108 views

sometimes Select / sometimes Position is faster

As you see, For list L, L1(Select method) is slower than L2(Position method). But for list <...
imida k's user avatar
  • 4,315
2 votes
0 answers
352 views

How to test for arguments for a pattern that is of a positive Integer OR Infinity so that both filter through to the definition on RHS?

How can I filter an argument of a function so that definition works on positive Integers (y >= 0) or Infinity? It will ...
Jules Manson's user avatar
  • 2,467
2 votes
0 answers
82 views

How to specify complicated patterns in function arguments?

Unfortunately, I have not found in documentation how to create complicated patterns in arguments of a function Consider a toy example. Say, I would like to have a simple function ...
Konstantin's user avatar
2 votes
0 answers
116 views

Store pattern names in variables, and use them in Condition (/;)

I am trying to create patterns whose form is not hard-coded, and which are not explicitly directly written. For that I want to use one list of pattern names to name some parts of a ...
abcd's user avatar
  • 483
2 votes
0 answers
77 views

pattern test on position

At the moment I'm using something like this to get the positions of entries of a matrix satisfying a specific value: ...
Peter Müller's user avatar
2 votes
0 answers
71 views

'Cases' command does not recognize specified patterns

I am having a problem with the "Cases" command. If I execute the following code ...
user195583's user avatar
2 votes
0 answers
133 views

Simple questions about Pattern and MatchQ

1st Question : Note that ...
imida k's user avatar
  • 4,315
2 votes
0 answers
48 views

What sorts of expressions can be Solve'd for?

We can Solve for expressions that match _Symbol, as in Solve[x^2+1 == 0, x]—but we can also ...
thorimur's user avatar
  • 9,020
2 votes
0 answers
45 views

Pattern with alternative heads

This works: ...
H.v.M.'s user avatar
  • 1,093
2 votes
0 answers
71 views

How to produce an error message for each argument?

I want to print a helpful message for every wrong input. How do you compactly implement a function with custom pattern constraints, default values and error messages for each argument separately? For ...
Mauricio Fernández's user avatar
2 votes
0 answers
57 views

recursively find StringCases

Can I recursively extract StringCases[] that match a specific pattern? Here is a minimalist example (not my actual problem): input ...
Conor Cosnett's user avatar
2 votes
0 answers
103 views

How does Mathematica choose which function definition to use?

I was wondering what the process of matching function arguments arguments against different function definitions actually looks like for Mathematica. (Just to be clear, I'm not simply looking for an ...
thorimur's user avatar
  • 9,020
2 votes
0 answers
39 views

Pattern match SubValues with unspecified number of arguments

Does there exist a single pattern that would match SubValues of arbitrary "length" with a given head? For example, I would like to match all of the ...
Hausdorff's user avatar
  • 3,535
2 votes
0 answers
53 views

KeyUnion by equivalent patterns

I have associations whose keys are patterns. For example, ass1 = <|a_ -> 1, f[] -> 3|>; ass2 = <|b_ -> 2|>; I would like to construct the ...
QuantumDot's user avatar
  • 19.7k
2 votes
0 answers
55 views

How to find consecutive things in nested expressions?

To find things that are consecutive you can use SequenceCases: ...
user5601's user avatar
  • 3,675