Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2005
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2005

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

Search the Archive

Re: pattern matching all list elements but last

  • To: mathgroup at smc.vnet.net
  • Subject: [mg54562] Re: [mg54539] pattern matching all list elements but last
  • From: "Wolf, Hartmut" <Hartmut.Wolf at t-systems.com>
  • Date: Wed, 23 Feb 2005 03:11:33 -0500 (EST)
  • Sender: owner-wri-mathgroup at wolfram.com

>-----Original Message-----
>From: Trevor Baca [mailto:trevorbaca at gmail.com] 
To: mathgroup at smc.vnet.net
>Sent: Tuesday, February 22, 2005 10:25 AM
>To: mathgroup at smc.vnet.net
>Subject: [mg54562] [mg54539] pattern matching all list elements but last
>
>hi mathgroup folks,
>
>let's say ls looks like this:
>
>  ls = {{1}, {2,3}, {4,5,6}, {7,8,9,10}}
>
>is there an elegant way to match all integers *except the last
>(rightmost)* in each list and, say, add 100 to each?
>
>  ls /. <magic replacement rule goes here>
>
>or
>
>  ls //. <magic replacement rule goes here>
>
>to give {{1}, {102,3}, {104,105,6}, {107,108,109,10}}?
>
>this works:
>
>  Release[ ls //. {a___, b_Integer, c___, z_Integer} :> {a, 
>Hold[b + 100], c, z} ]
>
>but is there a more elegant pattern, possibly one that avoids 
>the Hold-Release trick?
>
>
>trevor.
>
>


Again, what's elegant? Perhaps not to use pattern matching at all?


Just what springs to my mind:

	Join[Drop[#, -1] + 100, Take[#, -1]] & /@ ls

or, in different syntax:

	Join @@ ({100, 0} + Through[{Drop, Take}[#, -1]]) & /@ ls



Trying pattern matching, it seems to be natural to confine replacement
to level 1:

	Replace[ls, {a___, b_} :> Append[{a} + 100, b], {1}]

	Cases[ls, {a___, b_} :> (100 + {a}) ~Join~ {b}]

Effectively, these are the same rules, though quite different functions.


ReplaceList allows to march through the list (and collect in a list):

	ReplaceList[ls, {___, {a___, b_}, ___} :> Append[{a} + 100, b]]


--
Hartmut Wolf


  • Prev by Date: Graphic resizing problem Linux notebook
  • Next by Date: Re: Re: Re: Bug in 5.1??
  • Previous by thread: Re: pattern matching all list elements but last
  • Next by thread: Re: pattern matching all list elements but last