Re: How to use Pick[]; Is this a bug?
- To: mathgroup at smc.vnet.net
- Subject: [mg127810] Re: How to use Pick[]; Is this a bug?
- From: awnl <awnl at gmx-topmail.de>
- Date: Thu, 23 Aug 2012 20:50:14 -0400 (EDT)
- Delivered-to: l-mathgroup@mail-archive0.wolfram.com
- Delivered-to: l-mathgroup@wolfram.com
- Delivered-to: mathgroup-newout@smc.vnet.net
- Delivered-to: mathgroup-newsend@smc.vnet.net
- References: <k14kr3$7ip$1@smc.vnet.net>
Hi,
just a followup to my previous answer to this...
> This same issue comes up anytime you use pattern matching. For
> example consider:
>
> In[2]:= data = RandomInteger[10, {3, 2}]
>
> Out[2]= {{9, 2}, {0, 9}, {1, 3}}
>
> In[3]:= data /. {a_, b_} -> {a - b, a + b}
>
> Out[3]= {{7, 11}, {-9, 9}, {-2, 4}}
>
> My pattern looks for a two element list an replaces each two
> element list with the difference and sum of the elements it
> contains. And since the entire expression is a 3 element list
> with each element being a two element list, the entire list is
> not matched and I get the expected result.
>
> But look what happens if I drop the first element of data using Rest
>
> In[4]:= Rest[data] /. {a_, b_} -> {a - b, a + b}
>
> Out[4]= {{-1, 6}, {1, 12}}
>
> Now the pattern does match the entire list and I get a much
> different result. And like the example with Pick, I can specify
> the pattern as {a_Integer,b_} which will prevent matching the
> entire expression.
that's exactly one of those cases where I consider a "smarter pattern"
to be rather a workaround than a solution. An explicit level
specification is very often a much better solution, in this case it will
allow a solution that also work for reals, symbols or arbitrary expressions:
Replace[Rest[data], {a_, b_} -> {a - b, a + b},{1}]
and also, for example:
Replace[{{0.5, 0.2}, {x, f[y]}}, {a_, b_} -> {a - b, a + b}, {1}]
The point is that I think you should, whenever possible, be able to
separate the concerns of pattern matching and level specification...
regards,
albert