MathGroup Archive 2006

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

Search the Archive

Re: perplexed by blank sequence in pattern replacement


Blake schrieb:
> Dear MathGroup:
> 
> I have been blithely using blank sequences in pattern matching for some
> time. In persuit of a bug in a package of mine, I was quite alarmed to
> find that I don't really understand how to use the blank sequence, as
> expressed in the following simplified example:
> 
> In[1]:=Replace[a*b*c,Times[mysequence__]:>{mysequence}]
> 
> Out[1]={a b c}
> 
> I expected Out[1]={a,b,c}, from a naieve reading of the full form of
> a*b*c
> 
> In[2]:=FullForm[a*b*c]
> 
> Out[2]//FullForm=Times[a,b,c]
> 
> Will someone PLEASE tell me why In[1] does not yield the results I
> expected? (I can readily use a work-around, what I am concerned with is
> a correct understanding of pattern matching).

The reason is  Times[mysequence__] is immediately stripped to 
mysequence__ . Its only one factor present.

Make it a habit to use HoldPattern in order to prevent unrequested 
evaluation of the left hand pattern in Rule

In[1]:=Replace[a*b*c,HoldPattern[Times[mysequence__]]:>{mysequence}]

  Out[1]={a, b, c}

An unambigous way to exclude pattern evaluation is use of characteristic 
Head on the left and head replacement using Apply on the right side in Rule


Replace[a*b*c, expr_Times :> List@@expr]


-- 

Roland Franzius


  • Prev by Date: Re: too many special linear matrices->error in number
  • Next by Date: Re: position lists
  • Previous by thread: RE: perplexed by blank sequence in pattern replacement
  • Next by thread: Re: perplexed by blank sequence in pattern replacement