Re: pattern matching all list elements but last

• To: mathgroup at smc.vnet.net
• Subject: [mg54572] Re: [mg54539] pattern matching all list elements but last
• From: Andrzej Kozlowski <akozlowski at gmail.com>
• Date: Wed, 23 Feb 2005 03:11:43 -0500 (EST)
• References: <200502220924.EAA10849@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On 22 Feb 2005, at 10:24, Trevor Baca wrote:

> 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.
>
>

Of course elegence is in the eye od the beholder, but certainly there
are many ways not using Hold and Release:

ls = {{1}, {2, 3}, {4, 5, 6}, {7, 8, 9, 10}};

Method 1.

ls /. {(a___)?NumberQ,  (b_)?NumberQ} :>  Flatten[{{a} + 100, b}]

{{1}, {102, 3}, {104, 105, 6}, {107, 108, 109, 10}}

Method 2.

ls /. (x_)?VectorQ :> Append[Most[x] + 100, Last[x]]

{{1}, {102, 3}, {104, 105, 6}, {107, 108, 109, 10}}

Method 3 (same idea as 2)

Cases[ls, x_List :> Append[Most[x] + 100, Last[x]], 2]

{{1}, {102, 3}, {104, 105, 6}, {107, 108, 109, 10}}

Andrzej Kozlowski
Chiba, Japan
http://www.akikoz.net/andrzej/index.html
http://www.mimuw.edu.pl/~akoz/

```

• Prev by Date: Re: Saving file problem
• Next by Date: Re: Printing numbersDavid Bailey,dbaileyconsultancy.co.uk
• Previous by thread: Re: pattern matching all list elements but last
• Next by thread: Re: pattern matching all list elements but last