0
$\begingroup$

If I have a list

p={{15/16,1/4},{3/4,13/64},{3/4,1/4},{3/16,1/64},{3/16,1/16},{0,1/64}} 

I apply a function f[x_,y_]:=2 x-5 y; on it by command 4^3 f@@@p so i got

 {40,31,16,19,4,-5}

I want to sort p by using f. I try this command SortBy[p,f] but it gives

{{0,1/64},{3/16,1/64},{3/16,1/16},{3/4,13/64},{3/4,1/4},{15/16,1/4}}

, but i need actually

{{0,1/64},{3/16,1/16},{3/4,1/4},{3/16,1/64},{3/4,13/64},{15/16,1/4}} 

Please help in this sorting case, thank you in advance.

$\endgroup$
5
$\begingroup$

Just to amplify point:

f[x_, y_] := 2 x - 5 y;
g[{x_, y_}] := 2 x - 5 y

So (1. as Kub 2.redeine)

SortBy[p, f @@ # &]
SortBy[p, g]
$\endgroup$
5
$\begingroup$

You need to use

SortBy[list, Apply[f]]

By the way:

SortBy[list, f] sorts the elements of list in the order defined by applying f to each of them.

Is a little bit misleading because apply has a special meaning in Mathematica. Apply f at arg (f @@ arg) does something different than f @ arg. And the latter is what SortBy really does.

That is the problem of collision of common language with name choices made for basic Mathematica functions. To be consistent within Wolfram Language, but maybe less clear for a beginner, it should be:

SortBy[list, f] sorts the elements of list in the order defined by f composed with each of them.

As Compose is what that really is: Is there a name for #1@#2&?

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.