       Re: List manipulation question

• To: mathgroup at smc.vnet.net
• Subject: [mg15880] Re: [mg15852] List manipulation question
• From: David Withoff <withoff>
• Date: Wed, 17 Feb 1999 23:33:33 -0500
• Sender: owner-wri-mathgroup at wolfram.com

```> 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?
>
> Thanks for any help
>
>
> Maarten van der Burgt
> Icos Vision Systems
> Leuven
> Belgium
>
>
> In:=Swap23[L_List]:=Module
>         [
>           {temp},
>            temp = L[];
>           L[]=L[];
>           L[] =temp;
>           L
>         ]
>
> In:= mylist = {1,2,3};
>
> In:= 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= {1,2,3}
>
> In:=   temp = mylist[];
>           mylist[]=mylist[];
>           mylist[] =temp;
>           mylist
>
> Out= {1,3,2}

Swap23 is an assignment operation (it assigns a new value to mylist),
and like all assignment operations must hold the argument unevaluated
in order to work.  Also, the argument will be the symbol that is getting
a new value, not the expression that results after that symbol has
been evaluated.

For example, you could use

In:= Swap23[L_Symbol]:=Module[
{temp},
temp = L[];
L[]=L[];
L[] =temp;
L
]

In:= mylist = {1,2,3};

In:= Swap23[Unevaluated[mylist]]

Out= {1, 3, 2}

or you could set the HoldFirst attribute so that the argument will be held
unevaluated by default, as in:

In:= SetAttributes[Swap23, HoldFirst]

In:= Swap23[mylist]

Out= {1, 2, 3}

The need to hold the argument unevaluated in assignment operations is
a logical necessity in all programming languages, since a function can
only change the value of a variable if it knows what the variable is.
All of the assignment functions in Mathematica (Set, SetDelayed,
Increment, etc.) have attributes set for holding arguments unevaluated.

Dave Withoff
Wolfram Research

```

• Prev by Date: Re: QM,physics, mathematica
• Next by Date: Help - Single Variable Calc
• Previous by thread: RE: List manipulation question
• Next by thread: Re: List manipulation question