MathGroup Archive 2009

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

Search the Archive

Re: Re: ReplacePart except first element?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg102135] Re: [mg102085] Re: ReplacePart except first element?
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Thu, 30 Jul 2009 05:33:28 -0400 (EDT)

Works for me, too, when I use v6. I was using 5.2.

----- DrMajorBob <btreat1 at austin.rr.com> wrote:
> Works for me:
> 
> h[x_, a_] := ReplacePart[x, a -> x[[a]] + 1]
> 
> h[{1, 2, 3}, 1]
> 
> {2, 2, 3}
> 
> h[{1, 2, 3}, 2]
> 
> {1, 3, 3}
> 
> h[{1, 2, 3}, 3]
> 
> {1, 2, 4}
> 
> Bobby
> 
> On Wed, 29 Jul 2009 04:08:40 -0500, Ray Koopman <koopman at sfu.ca> wrote:
> 
>> On Jul 27, 11:03 pm, mokambo <alexandrepassosalme... at gmail.com> wrote:
>>> I was trying to modify a list by adding 1 to a certain element.
>>> I can't understand the following result:
>>>
>>> h[x_List, a_Integer] := ReplacePart[x, a -> x[[a]] + 1]
>>>
>>> h[{1, 2, 3}, 2] gives {,3,3} (what happened to the first element?) but
>>> h[{1, 2, 3}, 1] gives {2,2,3} as expected.
>>>
>>> Eventually I changed to:
>>>
>>> h[x_List, a_Integer] := MapAt[Function[y, y + 1], x, a]
>>>
>>> but the ReplacePart version still puzzles me.
>>> Is it because ReplacePart creates a copy instead of altering inline
>>> like x[[a]] = val does?
>>
>> I don't know why
>>
>>   h[x_,a_] := ReplacePart[x, a -> x[[a]] + 1]
>>
>> gave you what you posted. I get an error message
>> and then the input with the Rule evaluated:
>>
>>   h[{1,2,3}, 1]
>>
>>   ReplacePart::argt:
>>    ReplacePart called with 2 arguments; 3 or 4 arguments are expected.
>>
>>   ReplacePart[{1,2,3}, 1 -> 2]
>>
>> Here are three versions, all of which do what you want:
>>
>>   h[x_,a_] := MapAt[#+1&, x, a]
>>
>>   h[x_,a_] := ReplacePart[x, x[[a]]+1, a]
>>
>>   h[x_,a_] := x /. (x[[a]] -> x[[a]] + 1)
>>
>  
> -- 
> DrMajorBob at bigfoot.com


  • Prev by Date: Determining Frequency Distributon and Applying Rules
  • Next by Date: Re: Re: The audience for Mathematica (Was: Re: Show doesn't work inside
  • Previous by thread: Re: Re: ReplacePart except first element?
  • Next by thread: mimic InterpolatingFunction et. al. formatting