MathGroup Archive 2006

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

Search the Archive

Re: A question about pattern-matching

  • To: mathgroup at smc.vnet.net
  • Subject: [mg63738] Re: A question about pattern-matching
  • From: albert <awnl at arcor.de>
  • Date: Fri, 13 Jan 2006 04:48:14 -0500 (EST)
  • References: <djcgcs$6du$1@smc.vnet.net> <200510230946.FAA10826@smc.vnet.net> <dq5417$acm$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Hi,
 
> I'd expect this one to return the list of lists of ordered pairs. It
> returns the full testList:
> 
> testList /. {{(z_)?NumberQ, x:{{_Real, _Real}...}} -> x}
> 
> On the other hand, this one returns only the lists of ordered pairs:
> 
> testList /. {{(z_)?NumberQ, x:{{_, _}...}} -> x}
>

the first pattern does not match because some of the numbers in your orderd
pairs are Integers, _not_ Reals. The following works:

testList /. {{z_?NumberQ, x : {{_?NumericQ, _Real} ...}} -> x}
 
> I thought that one was free to "type" the parts of the pattern to
> return. 

you can, but you need to be more carefull...

> I also thought that naming the parts rather freely was allowed. 
> The first three of the following return what I would expect, but the
> last one, in naming the first of the ordered pairs' elements, returns
> the testList apparently unchanged:
> 
> In[54]:=
> 
> testList /. {{z_, {x:{_, _}...}} -> z}
> 
> testList /. {{z_, {x:{_, _}...}} -> x}
> 
> testList /. {{z_, x:{{_, _}...}} -> x}
> 
> testList /. {{z_, {x:{a_, _}...}} -> x}
> 

again, everything works as designed, I think. The problem is not with the
naming per se. Introducing the a-naming, the pattern will only match, when
the first entry in all orderd pairs is the same, maybe evaluating the
following two examples will clarify this:

{{1, 2}, {1, 3}, {1, 4}} /. {x : {a_, _} ...} -> x
{{2, 2}, {1, 3}, {1, 4}} /. {x : {a_, _} ...} -> x

in fact at first I was surprised that 

testList /. {{z_, {x:{_, _}...}} -> x}

actually works, but this is because of precedence of : and ... is different
from what I was naivly expecting, compare:

testList /. {{z_, {x:({_, _}...)}} -> x}
testList /. {{z_, {(x:{_, _})...}} -> x}

Anyway, the following should do what you want:

testList /. {{z_?NumberQ, x : {{_?NumericQ, _?NumericQ} ...}} :> Last /@ x}

depending on how well determined the structure of your data is, it might be
a good idea to restrict the replacing to a certain level of your data
(could well be faster for large datasets, too), e.g.:

Replace[
 testList, 
 {{z_?NumberQ, x : {{_?NumericQ, _?NumericQ} ...}} :> Last /@ x}, 
 {1}
]

hth

albert






  • Prev by Date: Re: problem with numerical values in Solve/NSolve
  • Next by Date: Re: Confusing behaviour with caching of evaluated expressions ?
  • Previous by thread: Re: A question about pattern-matching
  • Next by thread: Re: A question about pattern-matching