Re: How to specify "arbitrary depth" for a (sub)pattern?

• To: mathgroup at smc.vnet.net
• Subject: [mg113975] Re: How to specify "arbitrary depth" for a (sub)pattern?
• From: Oliver Ruebenkoenig <ruebenko at wolfram.com>
• Date: Fri, 19 Nov 2010 06:59:02 -0500 (EST)

```On Fri, 19 Nov 2010, kj wrote:

>
> Given some pattern P, what's the pattern Q[P] such that
> MatchQ[X, Q[P]] will evaluate to True if and only if either X or
> any of its subexpressions match P?
>
> Here's a common situation where I want this sort of pattern Q[P].
>
> Suppose that I have a list L, defined like this (for example):
>
> In[1]:= L = {1, a + b, 2, (a + b)^2, 3, (a + b)^2/c, 4, Sin[(a + b)^2/c]};
>
> ...and I want to extract from L all those members that contain (at
> any depth) an expression whose head is Plus.  I.e., I want to get
> the list
>
> {a + b, (a + b)^2, (a + b)^2/c, Sin[(a + b)^2/c}
>
> This seems like a job for Cases, but I don't know how to specify the
> right pattern for it to get the desired result:
>
> In[2]:= Cases[L, _Plus]
> Out[2]= {a + b}
>
> Passing a levelspec to Cases won't do the trick:
>
> In[3]:= Cases[L, _Plus, Infinity]
> Out[3]= {a + b, a + b, a + b, a + b}
>
> In other words, what I really need here is Cases[L, Q[_Plus]], but
> I don't know how to specify it.

Try,

Select[L, ! FreeQ[#, Plus] &]

Hth,
Oliver

>
> TIA!
>
> ~kj
>
>

```

• Prev by Date: Re: How to work with In?
• Next by Date: Re: band pass or notch filtering?
• Previous by thread: Re: How to specify "arbitrary depth" for a (sub)pattern?
• Next by thread: Re: How to specify "arbitrary depth" for a (sub)pattern?