# Questions tagged [pattern-matching]

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

996 questions
3k views

### What best practices or performance considerations are there for choosing between Cases, Position, Pick and Select?

Cases, Select,Pick and Position each have different ...
5k views

### Using a PatternTest versus a Condition for pattern matching

My last question to the site resulted in several answers that involve using pattern matching in Mathematica, a feature I wasn't very familiar with at the time. I am currently reading Mathematica ...
2k views

### How to generally match, unify and merge patterns?

This question was split from this one. While that question is now about how to match two particular patterns (mostly using Verbatim or ...
2k views

### How is pattern specificity decided?

Mathematica has a notion of pattern specificity, which is a partial ordering on patterns. The rules (e.g. DownValues, SubValues,...
4k views

### Find zero crossing in a list

I'm looking for a function that finds the index of the zero-crossing points of a list. Before I go making my own subroutine to do this, I was wondering if anyone knows of any built-in Mathematica ...
993 views

### Why is StringExpression faster than RegularExpression?

Edit: as noted by Albert Retey the performance difference is only seen when sub expression extraction is performed. If this test is used below the timings are similar: ...
5k views

### Looking for “Longest Common Substring” solution

I'm looking for robust code to solve the "Longest Common Substring" problem: Find the longest string (or strings) that is a substring (or are substrings) of two or more strings. I can just code it ...
3k views

### How do I perform string matching and replacements?

What are, and how do I use Mathematica's string matching and replacement tools?
745 views

### Why (and when) does pattern matching with f[__] perform MUCH more quickly than _f?

Consider this expression in Mathematica 10.3 (and above) on MacOS X: expr = a b c d e f g h i j k l m n o p q r s t myG[u] myF[a, b] Now compare the time it ...
2k views

### How to Combine Pattern Constraints and Default Values for Function Arguments?

EDIT: As several respondents have noted in the answers and comments below, the original example had a default value that would never be used because of the way patterns and default values are ...
3k views

### Fetching data from HTML source

I want to generate a couple of plots/graphs with Area 51 statistics. Since Area 51 doesn't work with the SE API, I'm forced to find another way to get the information I want. That other way is with <...
646 views

### Why doesn't PatternTest work with Composition?

While playing around with the solutions to this question, I've found some very strange behaviour: ...
733 views

### How can I ensure that I am constructing patterns in the most efficient way possible?

Inspired by this answer, I am interested to know if there are best practices or rules of thumb for constructing patterns, for example for use in function definitions (...
4k views

### Find subsequences of consecutive integers inside a list

I have a list which is something like this: {3,4,5,6,7,10,11,12,15,16,17,19,20,21,22,23,24,42,43,44,45,46} What I'd like to to is get the intervals which are in ...
2k views

### Using patterns in pure functions

Pure functions may be handy if you don't want to assign your function a name. For example I would calculate $x(x-1)$ for some numbers $x$ by ...
2k views

### Pattern to match a non-empty list of non-empty lists

Is there a pattern to match a list of lists, containing at least one list, with each list containing at least one element? In the Mathematica documentation it says that the pattern ...
317 views

### Strange behavior with Cases and Position with SetDelayed

I feel like I must be missing something simple and obvious here, but this has me scratching my head. This works as expected: ...
2k views

### replacement rules from a pattern and a matching expression

(This seems to be a very basic necessity in a language having pattern-matching capabilities such as Mathematica, yet I struggled for many hours to find a common solution to this problem.) Suppose ...
333 views

### Count works differently depending on how an association was created

Bug introduced in 10.4 and fixed in 11.3.0 I create two associations, that are supposed to be exactly the same. And then I want to count the elements at the second level. And I get different results: ...
1k views

### Elegant and fast way to join all string sequences

I want to do what title says: {"a","b",1,2,3,4,"a",2,2,2,"edg","?"} => {"ab",1,2,3,4,"a",2,2,2,"edg?"} in the most elegant way. For example one replacement rule for ...
566 views

### Is there a GraphicsPrimitiveQ (or a complete list of Heads of graphics primitives)?

For various reasons related to workflow associated with creating figures for journals, I am creating functions that will accept graphics primitives and a set of options and spit out a ...
467 views

### Version inconsistency with optional arguments: what if the default value doesn't match the pattern?

I just came across some weird behaviour. Take this function definition: ClearAll[f] f[vs_List : All] := "match" The default value of ...
2k views

### Detecting patterns of black and white stones on a 2D board

I'm writing a program to play a game of Pente, and I'm struggling with the following question: What's the best way to detect patterns on a two-dimensional board? For example, in Pente a pair of ...
1k views

### Detecting components in timeseries

I'm looking at this sequence of values: I'd like to detect the points where the center of the time-series shifts (around x=1000 and x=2000). Many of the transforms and smoothing methods I have tried ...
838 views

### How can a big table be treated as a database?

I often work with big tables that I want to treat kind of like a database. Here's an example table. ...
752 views

### Mysterious behaviour of Pick

As everyone knows, Pick can do amazing things, The most fascinating phenomenon is that it can pick though all sorts of lists: The basic & pattern matching: <...
2k views

### How to match a pattern with a pattern?

UPDATED This question is about: "What is the pattern to match a pattern-definition, exactly as it is written?" My original question is now split according to Mr.Wizards insightful answer below. This ...
432 views

### Pattern does not match with Orderless head

Why does the following pattern matching not succeed? ...
488 views

### What does f_[whoCalled]^:=f really mean?

I came across the following post by John Doty in this Google Groups discussion: On Friday, January 11, 2013 8:23:16 PM UTC-7, amzoti wrote: It is clear the Mathematica uses Lisp as one ...
297 views

### Can Mathematica convert a RegularExpression into a StringExpression or vice-versa?

I know that Mathematica can perform string comparison using either StringExpression or RegularExpression. Although regular ...
264 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, ...
6k views

### The difference between 0. and 0

I have a function for which 0 is a special case: f[A___, 0, B___] := 0 But since I am doing numerics, sometimes in the course ...
963 views

### Quick way to use conditioned patterns when defining multi-argument function?

I have a simple function that is supposed to only accept numeric values (i.e. complex/real numbers and constant symbols e.g. Pi, E). $$f(a,b,c)=a+b+c$$ Edit: I should have chosen a less simple ...
3k views

### Determine whether some expression contains a given symbol

Given a symbol t and an expression expr, how can I determine whether or not the symbol t ...
689 views

### MatchQ-ing Associations (MMA 10)

Consider {x->1} which has FullForm List[Rule[x, 1]] and, therefore, ...
924 views

### Position of a pattern-matched part of an expression

What you have A pattern, with certain part of it labeled As an example — Label: wally ...
274 views

### How to get Cases to wrap results in an arbitrary head?

A number of functions provide for results to be wrapped in an arbitrary head. This is very important in cases where the results should not be evaluated. Take Level...
1k views

### How to define a recursive pattern?

I want to translate this recursive syntactic definition into a Mathematica pattern1: $$\mathtt{x}: \begin{cases} \text{Null}\\ \{\textit{integer}, \mathtt{x}\} \end{cases}$$ In other ...
4k views

### Finding the period of an array of integers

A simple array of integers is given. The problem is to detect if a pattern is repeatedly occurring in the array, and find the length of that pattern. For example, for ...
542 views

### Pattern that matches colors

Suppose I'm writing a function that takes a color as a parameter; for example: drawShape[color_] := Graphics[{Style[Disk[], color]}]; But if the caller inputs an ...
2k views

### How to use subscript in pattern names?

For example I want to define a function with parameters σx and σy, that is, the function will be declared as: f[σx_,σy_] := . . ....
356 views

### What is the difference between defining a function and specifying the type of argument, versus applying a test to that argument?

Say I want to create a function that evaluates differently based on what type of argument is given. I've found two ways of doing this, ...
671 views

### Splitting a list

Please consider the following list: data={1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}; Now I would like to split the list into 0-sequences and Not-0-sequences as following: ...
3k views

### Passing down arguments

In R, one can use ... to pass arguments down to another function. For example ...
631 views

### How to enumerate all possible binary associations?

Suppose I have a list of symbols like: {a,b,c,d} I would like to enumerate all possible binary associations (combining symbols and/or sublists pairwise): ...
453 views

### Why is ReplaceAll behaving like this?

I'm learning to use the ReplaceAll function and I found the behavior of which is quite confusing. For Sqrt[f[x, y]] /. f[___] -> u Mathematica returns <...
4k views

### Should I use \\\“ or \” to match " in RegularExpression?

Both of the following return True: ...
226 views

### Orderless and Sequence

I just ran into the following subtlety. Let us consider a function f with attribute Orderless. ...