MathGroup Archive 2005

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

Search the Archive

Re: Pattern matching in functions

  • To: mathgroup at smc.vnet.net
  • Subject: [mg54491] Re: [mg54379] Pattern matching in functions
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Tue, 22 Feb 2005 04:22:51 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

>-----Original Message-----
>From: Maximilian Ulbrich [mailto:mulbrich at berkeley.edu] 
To: mathgroup at smc.vnet.net
>Sent: Saturday, February 19, 2005 8:33 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg54491] [mg54379] Pattern matching in functions
>
>Hi,
>
>I would like to find subexpressions using Cases.
>In the following case, I expected to find a[b] and a[c] and therefore
>get {b,c} as the result. However, I get {l,l}.
>What happens and how can I solve this?
>
>Cases[l^4*a[b][l] + l*a[c][l], x_a[y_] -> y, {0, Infinity}]
>
>Thanks,
>Max
>
>

Max,

to easier understand what happend, first remove the transformation from
your pattern:

In[11]:=
Cases[l^4*a[b][l] + l*a[c][l], x_a[y_], {0, Infinity}]
Out[11]= {a[b][l], a[c][l]}

so e.g. x_a matches to a[b], y_ to 1, and you'll finally get {1, 1}
after the transformation. 

x_a can only match to an expression with head a, such the only
subexpressions that might match to x are a[b] and a[c].


Now if we release that condition (which you obviously haven't meant), we
still don't get the right matches:

In[12]:=
Cases[l^4*a[b][l] + l*a[c][l], x_[y_], {0, Infinity}]
Out[12]= {a[b][l], a[c][l]}


Why not? a[b] e.g. is the head of the expression a[b][1], but Cases has
the option

In[16]:= Options[Cases]
Out[16]= {Heads -> False}

such the pattern x_ is not tried to match *within* a head.


It's easy to change the option:

In[13]:=
Cases[l^4*a[b][l] + l*a[c][l], x_[y_], {0, Infinity}, Heads -> True]
Out[13]= {a[b], a[b][l], a[c], a[c][l]}


So now we get all matches, those you desired and those you didn't. If
you only want matches to a[b], a[c] then your pattern should be more
specific:

In[17]:=
Cases[l^4*a[b][l] + l*a[c][l], a[y_], {0, Infinity}, Heads -> True]
Out[17]= {a[b], a[c]}


Now, of course, if you leave out here Heads -> True, then you'll get no
matches:

In[18]:=
Cases[l^4*a[b][l] + l*a[c][l], a[y_], {0, Infinity}]
Out[18]= {}


I guess that was your problem in first place.


--
Hartmut Wolf


  • Prev by Date: Re: The two dices
  • Next by Date: Re: The two dices
  • Previous by thread: Re: Pattern matching in functions
  • Next by thread: Mathematica 5.0 on Mandrake and Numlock