MathGroup Archive 1997

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

Search the Archive

Re: Sort[]

  • To: mathgroup at smc.vnet.net
  • Subject: [mg8593] Re: [mg8540] Sort[]
  • From: David Withoff <withoff>
  • Date: Sun, 7 Sep 1997 22:13:12 -0400
  • Sender: owner-wri-mathgroup at wolfram.com

> Hello,
>
> I need to Sort[] lists that contain symbols.
>
> I've noticed the following strange feature of Sort[].
> Take a simple list
> myList = {b, -b}; Sort gives a result in canonical order
>
> Sort[myList]
>
> {-b,b}  or
>
> Sort[myList, Less]
>
> {b,-b}
>
> Take now a simple list
>
> myList1 = {-b, b}; Then, Sort gives the same correct result
>
> Sort[myList1]
>
> {-b,b}
>
> while Sort[] with Less argument gives incorrect result.
>
> Sort[myList1, Less]
> {-b,b}
>
> Can someone explain what is the problem and how to deal with it?

The Sort function is designed so that elements will be re-ordered
only if the sorting test evaluates to False.  Since the elements
here are symbolic, the comparisons Less[b, -b] and Less[-b, b]
will evaluate to themselves (that is, Less[b, -b] just returns
Less[b, -b]), so Sort leaves the original order unchanged.
For example:

In[1]:= Sort[{4,3,2,5,6,5,3,4}, f]

Out[1]= {4, 3, 2, 5, 6, 5, 3, 4}

The order is left alone here because the sorting test f doesn't
have a definition, and so never evaluates to False.

> I also need to work with list where symbols are declared Positive
> (or Negative) etc. For instance, declare c Negative:
>
> Sign[c]^=-1;
> Then,
>
> Sort[{-c, c}] should give {c, -c}
>
> How to Sort those lists? Is there a way to use Sort[]
> or I have to write my own function.

If you don't specify a sorting test, then Sort will use the default
sorting test, which does not call Sign, and will ignore the rule
that you added for Sign[c].  If you want a sorting test that will
use the rules that you have added, you can include that sorting
test in the second argument of Sort, as in

In[2]:= Sign[c]^=-1;

In[3]:= Sort[{-c, c}, Sign[#1] <= Sign[#2] &]

Out[3]= {c, -c}

Dave Withoff
Wolfram Research


  • Prev by Date: Re: MatchQ
  • Next by Date: Re: NDSolve
  • Previous by thread: Sort[]
  • Next by thread: MatchQ