Re: Replace, test question
- To: mathgroup at smc.vnet.net
- Subject: [mg120351] Re: Replace, test question
- From: Heike Gramberg <heike.gramberg at gmail.com>
- Date: Tue, 19 Jul 2011 07:00:02 -0400 (EDT)
- References: <201107181013.GAA26882@smc.vnet.net>
With a pattern /; test construct you get a positive match if test itself =
evaluates to True, not test[pattern], so in this
case you would want test to be PrimeQ[x], not PrimeQ, e.g.
{58, 61, 15, 66, 10, 2, 24, 81, 45, 84} /. x_ /; PrimeQ[x] -> P
You could also have used a PatternTest which is of the form =
pattern?test, where you get a positive match if test[pattern] is
True, so in this case
{58, 61, 15, 66, 10, 2, 24, 81, 45, 84} /. x_?PrimeQ -> P
would give the same result as above.
Heike
On 18 Jul 2011, at 11:13, PA32R wrote:
> I'm very new to Mathematica and trying to work my way through it. I
> don't understand why:
> {58, 61, 15, 66, 10, 2, 24, 81, 45, 84} /. x_ /; PrimeQ -> P
> returns:
> {58, 61, 15, 66, 10, 2, 24, 81, 45, 84}
>
> I would expect it to take the list, replace everything in the list
> that matches any pattern and passes the PrimeQ test, i.e., is prime,
> with P to yield:
> {58, P, 15, 66, 10, P, 14, 81, 45, 84}
>
> Can someone explain my misunderstanding?
>
> Thanks.
>
- References:
- Replace, test question
- From: PA32R <tio540s1@gmail.com>
- Replace, test question