Re: Re: ReplaceAll reloaded
- To: mathgroup at smc.vnet.net
- Subject: [mg107407] Re: [mg107397] Re: [mg107363] ReplaceAll reloaded
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Thu, 11 Feb 2010 08:33:24 -0500 (EST)
- References: <hkeb04$t7v$1@smc.vnet.net> <4B6AB3AA.1080805@gmail.com>
Hi,
Thanks, I am well aware of the solution. For some reason, my post was cut and only the upper half appeared. I repeat it here:
n[3]:= Or[a,b]/.Or[x__]:>{x}//Trace
Out[3]= {{{Or[x__],x__},x__:>{x},x__:>
{x}},a||b/.x__:>{x},{a||b}}
<Or> on your pattern evaluates to the pattern itself before the match is
attempted. This is due
to the behavior of Or on any single argument - it just returns the argument.
To avoid this, you have
to prevent the evaluation of your rule's l.h.s. Either use HoldPattern:
In[4]:= Or[a,b]/.HoldPattern[Or[x__]]:>{x}
Out[4]= {a,b}
Or Verbatim
In[5]:= Or[a,b]/.Verbatim[Or][x__]:>{x}
Out[5]= {a,b}
or, possibly, wrap the entire rule in Unevaluated:
In[8]:= Or[a, b] /. Unevaluated[Or[x__] :> {x}]
Out[8]= {a, b}
Regards,
Leonid
On Thu, Feb 11, 2010 at 3:50 PM, <bsyehuda at gmail.com> wrote:
> you need to prevent the evaluation of Or on a single argument
>
> Or[x] returns x
> so in the rhs of the replacement rule Or[y__] returns y__
> so the rule itself is identical to Or[a,b] /. y__:> {y}
> and the result is clear
> two way to solve it
>
> Or[a,b]/.Or[x_,y_]:>{x,y}
> or possibly (for more than 2 variables)
> Or[a,b]/.Or[x_,y__]:>{x,y}
>
> but this is tedious and not a general solution
> the way to do it is to prevent the evaluation of the rhs, using HoldPattern
>
> Or[a,b]/.HoldPattern[Or[y__]]:>{y}
> and this returns {a,b}
> as required
>
> yehuda
>
>
> On Thu, Feb 11, 2010 at 2:08 PM, Leonid Shifrin <lshifr at gmail.com> wrote:
>
>> Istvan,
>>
>> all you need is to run Trace - it shows pretty clearly what happens:
>>
>> In[3]:= Or[a,b]/.Or[x__]:>{x}//Trace
>>
>> Out[3]= {{{Or[x__],x__},x__:>{x},x__:>{x}},a||b/.x__:>{x},{a||b}}
>>
>> <Or> on your pattern evaluates to the pattern itself before the match is
>> attempted. This is due
>> to the behavior of Or on any single argument - it just returns the
>> argument=
>>
>
>