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

learn more… | top users | synonyms (1)

58
votes
4answers
2k views
56
votes
4answers
3k 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 ...
48
votes
9answers
2k views

Injecting a sequence of expressions into a held expression

Consider the following toy example: Hold[{1, 2, x}] /. x -> Sequence[3, 4] It will give Hold[{1, 2, Sequence[3, 4]}] ...
44
votes
1answer
1k 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 ...
42
votes
2answers
860 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, ...
38
votes
6answers
2k 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 ...
31
votes
1answer
604 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: ...
29
votes
4answers
3k 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 ...
26
votes
1answer
937 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 ...
25
votes
2answers
518 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 (...
25
votes
1answer
484 views

Why doesn't PatternTest work with Composition?

While playing around with the solutions to this question, I've found some very strange behaviour: ...
24
votes
5answers
2k views

Fetching data from HTML source

I want to generate a couple of plots/graphs with Area51 statistics. Since Area51 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 ...
22
votes
2answers
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 ...
21
votes
5answers
673 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. ...
21
votes
4answers
1k 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 ...
20
votes
7answers
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 ...
20
votes
2answers
1k views

How do I perform string matching and replacements?

What are, and how do I use Mathematica's string matching and replacement tools?
19
votes
2answers
717 views

How to inject an evaluated expression into a held expression? [duplicate]

I know that there are methods to structurally manipulate held expressions (discussed e.g. here), but I failed to apply those for this particular problem: ...
19
votes
3answers
266 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 ...
19
votes
1answer
193 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: ...
19
votes
1answer
217 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 ...
18
votes
3answers
662 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 ...
18
votes
1answer
540 views

NotebookFind and String Pattern Expressions

Is there a way that NotebookFind can be used to match string pattern expressions rather than just strings? The documentation for ...
17
votes
5answers
2k 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 ...
17
votes
6answers
780 views

Split a string at specific positions

Given a string of alphanumerical characters, how to split it simply and quickly at the center of continuous letter-substrings? Is there an elegant and fast solutions out there in the "computational ...
17
votes
6answers
1k 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 ...
17
votes
4answers
482 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: ...
17
votes
4answers
974 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 ...
17
votes
2answers
409 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 ...
17
votes
1answer
955 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 ...
16
votes
4answers
751 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 ...
16
votes
1answer
308 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 ...
16
votes
1answer
253 views

Bug in RepeatedNull?

RepeatedNull appears to be buggy (versions 8.0, and 9.0). Define f as follows: ...
16
votes
1answer
353 views

Is pure pattern matching without PatternTest and Condition Turing-complete?

Note that this question is not a duplicate of that one. It is specifically about the pattern-matching engine, and explicitly excluding those patterns which call back into the full evaluation (i.e. ...
15
votes
3answers
473 views

Grabbing a number of characters around a string pattern

If I have some string data: text = StringTake[ExampleData[{"Text", "DeclarationOfIndependence"}], 400] "When in the Course of human events, it becomes ...
15
votes
6answers
768 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 ...
15
votes
2answers
475 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 ...
15
votes
2answers
499 views

Successful match in Replace but not in Cases?

I have a little example that exhibits a successful pattern match in ReplaceAll that Cases misses and I wonder if the assembled ...
15
votes
2answers
912 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_] := . . ...
15
votes
2answers
474 views

Pattern issues weird warning

Take for example head[b_[PatternSequence[_, _]]] := 9 I know this example serves no purpose as is. It also happens in useful examples such as ...
14
votes
6answers
2k views

Counting negative values in list

I would like to count the negative values of a list. My approach was Count[data, -_] which doesn't work. How can I tell Mathematica to count all numbers with ...
14
votes
3answers
382 views

Make mathematica treat $e_i^2$ as numeric

With NumericQ[symbol] = True, I can declare that a symbol is numeric. I want the expressions matching: $$e_{\text{i$\_$}?\text{IntegerQ}}^2$$ to be treated as ...
14
votes
3answers
257 views

What's wrong with this pattern of the form Except[Repeated[…]]?

I'm trying to build a head that recognizes molecules. Here's the code ...
14
votes
2answers
500 views

How to detect loops in a vector field?

Given a vector field and I'd like to detect if there are streamlines in closed patterns. For example, if the input is a vector field like this: ...
14
votes
5answers
764 views

Getting number of binary digits combinations without “forbidden” patterns

I need to get the number of all combinations of binary digits in an 8-digit binary number, but not including those that follow some "forbidden" patterns like these: ...
14
votes
4answers
712 views

Returning an unevaluated expression with values substituted in

Let's say I have a function formula[x_List] := (x[[1]] - x[[2]]) + (x[[3]] - x[[4]]); and I want to pass it a variable and get back the unevaluated formula with ...
14
votes
2answers
338 views

Pattern to match L, but not L[_]

I have an expression where I want to replace L but not L[_] For example, the following doesn't work and ...
14
votes
3answers
194 views

What does `: Hold[$IterationLimit]` mean?

In this answer, what does the : Hold[$IterationLimit] part of the following construct do? ...
14
votes
3answers
542 views

How to match a cyclically repeating sequence?

I have run across several times recently where I must match a sequence that is cyclically repeating. For example, with the sequence, Sequence[a, b, c] how would ...
14
votes
1answer
382 views

MatchQ-ing Associations (MMA 10)

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