MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

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

  • To: mathgroup at smc.vnet.net
  • Subject: [mg113974] Re: How to specify "arbitrary depth" for a (sub)pattern?
  • From: Peter Breitfeld <phbrf at t-online.de>
  • Date: Fri, 19 Nov 2010 06:58:50 -0500 (EST)
  • References: <ic5i8o$3su$1@smc.vnet.net>

This seems to work:

plusQ[x_]:=! FreeQ[x,_Plus]

Select[L,plusQ]

Out={a + b, (a + b)^2, (a + b)^2/c, Sin[(a + b)^2/c]}


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.
>
> TIA!
>
> ~kj
>

-- 
_________________________________________________________________
Peter Breitfeld, Bad Saulgau, Germany -- http://www.pBreitfeld.de


  • Prev by Date: Re: FindFit Mathematica 7
  • Next by Date: Re: How to work with In?
  • Previous by thread: How to specify "arbitrary depth" for a (sub)pattern?
  • Next by thread: Re: How to specify "arbitrary depth" for a (sub)pattern?