MathGroup Archive 2006

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

Search the Archive

Re: Re: List Help Needed

  • To: mathgroup at
  • Subject: [mg68894] Re: [mg68863] Re: List Help Needed
  • From: "Jean-Marc Gulliet" <jeanmarc.gulliet at>
  • Date: Tue, 22 Aug 2006 05:20:38 -0400 (EDT)
  • References: <ecbo4l$r5j$> <> <>
  • Sender: owner-wri-mathgroup at

On 8/21/06, Bharat Bhole <bbhole at> 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]}}



[2] "Level Specifications",

  • 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