开发者

how to use sort function the same way as max or min in mathematica

Please take a look at the following code:

Sort[{1, y, x}, Greater]
Max[{1, x, y}]
x = 1
y = 2
Sort[{1, y, x}, Greater]
Max[{1, x, y}]

It is interesting to note that the first Sort always produce a definite result while the first Max does not, even when Greater is specified. Note I have not given any numerical values for x and y. Why is this and how can I have a Sort function behave the same way as the Max (or Min) functi开发者_如何转开发on?

Thanks!

BTW, I am using Mma 7.0


From the help:

Sort orders symbols by their names, and in the event of a tie, by their context  

So, what you want is another function, not Sort[] ...

Edit

Here is a way to force only numerical sort under your premises:

sortN[s_, f_: (OrderedQ[{#1, #2}] &)] :=

 (*Check if everything is eval to a number*)
 If[And @@ (NumericQ /@ s),

  (*and then sort*)
  Sort[s, f],

  (*if something not numeric,
  reconstruct the function call and return it*)
  If[(ToString[f] == ToString[OrderedQ[{#1, #2}] &]), 
    Print[Unevaluated[sortN[s]]], Print[Unevaluated[sortN[s, f]]]];]

Usage:

In[120]:= sortN[{3,2,1,4}]
Out[120]= {1,2,3,4}

In[121]:= sortN[{3,2,1,Sin}]
Out[121]= sortN[{3,2,1,Sin}]

In[122]:= sortN[{1,2,3,4},Greater]
Out[122]= {4,3,2,1}

In[123]:= sortN[{1,2,3,Log},Greater]
Out[123]= sortN[{1,2,3,Log},Greater]  

Please be aware that

  1. Each Symbol in the list are going to be evaluated twice, once for checking if it's numeric, and then for sorting. That could be circumvented by storing the intermediate result before taking the NumericQ. Edit Thinking again, I'm not quite sure ... perhaps someone else can clarify on this one.

  2. An expression is considered a numeric quantity if it is either an explicit number or a mathematical constant such as Pi, or is a function that has attribute NumericFunction and all of whose arguments are numeric quantities. In most cases, NumericQ[expr] gives True whenever N[expr] would yield an explicit number.

  3. By changing NumericQ for StringQ or whatever you want (or adding it as a parameter for sortN[], you may select the Type you want to force and sort.


In this case Greater fails to evaluate, and Sort seems to treat unevaluated comparison function as if it were evaluting to True, ie the following give the same result

Sort[{a, c, d}, True &]
Sort[{a, c, d}, UndefinedFunction&]

As to why, it depends on the internals, here's an example how it could happen

If[!compare[a,b],swap[a,b],dontswap[a,b]]

You see that compare evaluating to True and not evaluating has the same effect. In general, boolean expression evaluating to anything besides True or False can give unpredictable results, so you need to make sure your boolean values get evaluated.

Here's another example of confusion that was caused by this issue

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜