MathGroup Archive 2004

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

Search the Archive

Re: ReplaceList -- Unexpected Answer

  • To: mathgroup at smc.vnet.net
  • Subject: [mg46796] Re: [mg46788] ReplaceList -- Unexpected Answer
  • From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
  • Date: Tue, 9 Mar 2004 04:30:40 -0500 (EST)
  • References: <200403080910.EAA10427@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On 8 Mar 2004, at 10:10, Harold Noffke wrote:

> MathGroup:
>
> In The Mathematica 5 Book, Section 2.3.3 Naming Pieces of Patterns, we
> find the following pattern matching exercise ...
>
> 	Now both arguments of f are constrained to be the same, and only the
> 	first case matches.
>
> 	In[5]:=
> 		{f[h[4], h[4]], f[h[4], h[5]]} /. f[x:h[_], x_] -> r[x]
> 	Out[5]=
> 		{r[h[4]],f[h[4],h[5]]}
>
>
> Now, let's use ReplaceList to get more insight into this matching
> process ...
>
> 	In[6]:=
> 		ReplaceList[ {f[h[4],h[4]],f[h[4],h[5]]},f[x:h[_],x_] -> r[x] ]
> 	Out[6]=
> 		{}
> 		
> I do not understand why ReplaceList returns {} instead of { r[h[4]] }.
>
> Regards,
> Harold
>
>
>
Because ReplaceList attempts to find all the ways to match your  
*entire* expression to the supplied pattern, and in your case there are  
no such matches. But

In[2]:=
ReplaceList[ f[h[4],h[4]],f[x:h[_],x_] -> r[x] ]

Out[2]=
{r[h[4]]}

If you want to match subexpressions as well as the entire expression  
you can use the the function ReplaceAllList defined in the  
documentation:

In[4]:=
ReplaceAllList[expr_,rules_]: 
=Module[{i},Join[ReplaceList[expr,rules],If[
     AtomQ[expr],{},Join@@Table[ReplacePart[expr,#,i]&/@ReplaceAllList[
       expr[[i]],rules],{i,Length[expr]}]]]]

then


In[5]:=
ReplaceAllList[{f[h[4],h[4]],f[h[4],h[5]]},f[x:h[_],x_]->r[x]]

Out[5]=
{{r[h[4]],f[h[4],h[5]]}}



Andrzej Kozlowski
Chiba, Japan
http://www.mimuw.edu.pl/~akoz/


  • Prev by Date: Re: Differences in Random Numbers
  • Next by Date: RE: ReplaceList -- Unexpected Answer
  • Previous by thread: ReplaceList -- Unexpected Answer
  • Next by thread: Re: ReplaceList -- Unexpected Answer