MathGroup Archive 2006

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

Search the Archive

Re: Re: List Help Needed

  • To: mathgroup at smc.vnet.net
  • Subject: [mg68894] Re: [mg68863] Re: List Help Needed
  • From: "Jean-Marc Gulliet" <jeanmarc.gulliet at gmail.com>
  • Date: Tue, 22 Aug 2006 05:20:38 -0400 (EDT)
  • References: <ecbo4l$r5j$1@smc.vnet.net> <200608211033.GAA10513@smc.vnet.net> <a3224ef10608210825t56f3d97u4449f36f88e8a9f6@mail.gmail.com>
  • Sender: owner-wri-mathgroup at wolfram.com

On 8/21/06, Bharat Bhole <bbhole at gmail.com> wrote:
> The solution given by you works when lst has three or more pairs. But it
> does not work with two pairs, i.e., with {{a,b},{c,d}}. Is there a simple
> replacement rule which gives the result desired here regardless of the
> number of elements in lst. This behavior of replacement rule seems
> arbitrary.

Hi Bharat,

you are right: the first solution I gave you, using replacement rules,
does not yield the expected result.

  lst= { { a,b}, { c,d}}; lst/. { x_,y_}-> { x, f[y]} returns {{a, b},
f[{c, d}]} rather than the expected list {{a, f[b]}, {c, f[d]}}. The
returned result is the correct one, indeed, since the replacement
operator /. looks for the most general patterns first and then goes
down to more and more specialised/restricted matches. Thus, applied to
a list of two lists only, the rule matches the list itself before the
individual sublists:

MatchQ[{{a, b}, {c, d}}, {x_, y_}] --> True
MatchQ[{{a, b}, {c, d}, {e, f}}, {x_, y_}] --> False

One way to avoid this pitfall is to add a test on one or more heads of
the elements of the sublists, assuming of course that they have the
regular and definite structure. For instance, say that the first
element is always an atom,

lst/. { x_?AtomQ,y_}-> { x, f[y]}
--> {{a, f[b]}, {c, f[d]}}

Another way is to use Replace [1] with a level specification [2]. In
the following example, we force Mathematica to start looking from the
lowest level of the expression:

Replace[ lst, { x_,y_}-> { x, f[y]}, -1]
--> {{a, f[b]}, {c, f[d]}}

Regards,
Jean-Marc

[1] http://documents.wolfram.com/mathematica/functions/Replace

[2] "Level Specifications",
http://documents.wolfram.com/mathematica/book/section-A.3.6


  • Prev by Date: Mathematica as a server via J/Link
  • Next by Date: Re: programming books / tutorials
  • Previous by thread: Re: List Help Needed
  • Next by thread: Re: Re: List Help Needed