Re: Sort within self-defined procedure
- To: mathgroup at smc.vnet.net
- Subject: [mg108619] Re: Sort within self-defined procedure
- From: Bill Rowe <readnews at sbcglobal.net>
- Date: Thu, 25 Mar 2010 04:26:54 -0500 (EST)
On 3/24/10 at 4:42 AM, postitdummy at arcor.de (dornakul) wrote:
>I am desperate. Why is it not possible to sort a list within a self-
>defined procedure?
>Here comes the minimal example
>In[188]:= ks[x_] = Module[{l},
>l = {1, 5, x, 2}; Sort[l, Greater]
>]
>Out[188]= {5, x, 2, 1}
>In[190]:= ks[20]
>Out[190]= {5, 20, 2, 1}
You are having problem because you used Set (=) when defining ks
instead of SetDelayed (:=). When you use Set, the left hand side
gets evaluated at the time you make the definition. So, the Sort
operation is done before x is assigned a value and not when ks
is called. By using SetDelayed, the Sort operation occurs after
x is given a value when ks is called which is what you want. As
a general rule, you should use SetDelayed when defining
functions not Set