MathGroup Archive 2010

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

Search the Archive

Re: Behavior of Longest

  • To: mathgroup at smc.vnet.net
  • Subject: [mg107945] Re: [mg107909] Behavior of Longest
  • From: Leonid Shifrin <lshifr at gmail.com>
  • Date: Wed, 3 Mar 2010 05:53:29 -0500 (EST)
  • References: <201003021254.HAA14195@smc.vnet.net>

Hi Daniel,

I don't think it's a bug. By using the form you did, you gave the
pattern-matcher no choice,
since there are no other placeholders (in the case of Shortest) to absorb
the rest of the elements.

In[502]:= {1, 2} /. {___, Longest[x__Integer], ___} :> f[x]

Out[502]= f[1, 2]

In[504]:= {1, 2} /. {Longest[x__Integer]} :> f[x]

Out[504]= f[1, 2]

I have an impression that the intended use is in a list, like in your second
example or in the following:

In[505]:= {1, 2} /. {Shortest[x__Integer]} :> f[x]

Out[505]= f[1, 2]

In[506]:= {1, 2} /. {___, Shortest[x__Integer], ___} :> f[x]

Out[506]= f[1]

In[507]:= {1, 2} /. {___, Shortest[x__Integer]} :> f[x]

Out[507]= f[2]

In the last two cases, there are placeholders to absorb "unused" elements,
and thus the pattern-matcher has a freedom it needs for Shortest. In fact,
in your first example you really did not apply rules at level 0  (entire
expression) - rather, they were applied at level 1, two times: for a
sequence <1>, and for a sequence <2>, separately:

In[509]:= Replace[{1, 2},
 Longest[x__Integer] :> (Print["Rule matched"]; f[x]), {0}]

Out[509]= {1, 2}

In[510]:= Replace[{1, 2},
 Longest[x__Integer] :> (Print["Rule matched"]; f[x]), {1}]

During evaluation of In[510]:= Rule matched

During evaluation of In[510]:= Rule matched

Out[510]= {f[1], f[2]}

Regards,
Leonid



On Tue, Mar 2, 2010 at 3:54 PM, dh <dh at metrohm.com> wrote:

> Hello,
> can somebody give an explanation for the following behavior of Longest
> (Mathematica version 7.0.1):
> {1, 2} /. Longest[x__Integer]:>{x}    gives {{1}, {2}}
>
> the same as Shortest:
> {1, 2} /. Shortest[x__Integer]:>{x}  gives {{1}, {2}}
>
> However, it works like expected in the following case:
> {a, 1, 2, b} /. {x1___, Longest[x__Integer], x2___} :> {x1, {x}, x2}
> gives: {a, {1, 2}, b}
>
> looks like a bug to me.
>
> Daniel
>
> --
>
> Daniel Huber
> Metrohm Ltd.
> Oberdorfstr. 68
> CH-9100 Herisau
> Tel. +41 71 353 8585, Fax +41 71 353 8907
> E-Mail:<mailto:dh at metrohm.com>
> Internet:<http://www.metrohm.com>
>
>
>



  • Prev by Date: Re: Behavior of Longest
  • Next by Date: Re: learning calculus through mathematica
  • Previous by thread: Re: Behavior of Longest
  • Next by thread: Re: Behavior of Longest