Re: ReplacePart except first element?
- To: mathgroup at smc.vnet.net
- Subject: [mg102085] Re: ReplacePart except first element?
- From: Ray Koopman <koopman at sfu.ca>
- Date: Wed, 29 Jul 2009 05:08:40 -0400 (EDT)
- References: <h4m4ar$eah$1@smc.vnet.net>
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)
- Follow-Ups:
- Re: Re: ReplacePart except first element?
- From: DrMajorBob <btreat1@austin.rr.com>
- Re: Re: ReplacePart except first element?