Re: List manipulation question
- To: mathgroup at smc.vnet.net
- Subject: [mg15893] Re: List manipulation question
- From: "Allan Hayes" <hay at haystack.demon.co.uk>
- Date: Wed, 17 Feb 1999 23:33:40 -0500
- References: <7a2b7v$1t6@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Maarten.vanderBurgt at icos.be wrote in message <7a2b7v$1t6 at smc.vnet.net>... > >Dear all, > >In the following piece of code I define a function Swap23 which is ment >to swap elements 2 and 3 in a list. >Executing the function on a simple list I get an error. Why do I get >this error? Why do I not get this error when I execute the commnad from >Swap23 "by hand" as is shown in In[4]? > >Thanks for any help > > >Maarten van der Burgt >Icos Vision Systems >Leuven >Belgium > > >In[1]:=Swap23[L_List]:=Module >[ > {temp}, > temp = L[[2]]; > L[[2]]=L[[3]]; > L[[3]] =temp; > L >] > >In[2]:= mylist = {1,2,3}; > >In[3]:= Swap23[mylist] > >Set::"setps": "\!\({1, 2, 3}\) in assignment of part is not a symbol." >Set::"setps": "\!\({1, 2, 3}\) in assignment of part is not a symbol." > >Out[3]= {1,2,3} The input Swap23[mylist] evaluatest mylist to get Swap[{1,2,3}] Then it passes {1,2,3} to L on the right, triggers a scoping change of temp to temp$ and gets Module[{temp$}, temp$ = {1, 2, 3}[[2]]; {1, 2, 3}[[2]] = {1, 2, 3}[[3]]; {1, 2, 3}[[3]] = temp$; {1, 2, 3} ] There are two problems here: 1) {1, 2, 3}[[2]] = {1, 2, 3}[[3]]; is not allowed: the form must be s[[2]] = .. where s is a symbol with a value previously assigned by Set (=), not SetDelayed(:=), and the value must have part 2. 3) the output is already fixed as {1,2,3}. Here is a version that works, and uses features of part setting, Swap23[L_List]:= Module[{temp = L}, temp[[{2,3}]]=L[[{3,2}]]; temp ] mylist = {1,2,3} Swap23[mylist] {1,3,2} > >In[4]:= temp = mylist[[2]]; > mylist[[2]]=mylist[[3]]; > mylist[[3]] =temp; > mylist > >Out[4]= {1,3,2} This works becaues mylist is a symbol with preset value {1,2,3} Allan --------------------- Allan Hayes Mathematica Training and Consulting www.haystack.demon.co.uk hay at haystack.demon.co.uk Voice: +44 (0)116 271 4198 Fax: +44 (0)870 164 0565