Karim Belabas on Tue, 20 Feb 2018 11:27:21 +0100 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: vecsort() and sign() |
* Max Alekseyev [2018-02-20 01:40]: > In the extended help for 'vecsort' I read: > "a comparison function (*t_CLOSURE*), with two arguments $x$ and $y$, and > returning an integer which is < 0, > 0 or = 0 if x < y, x > y or x=y > respectively. The *sign* function is very useful in this context:" > which is followed by examples like > ? vecsort(v, (x,y)->sign(abs(x)-abs(y))) \\ *sort by increasing absolute > value* > However, I do not see how sign() is useful here. From the definition of > vecsort(), it follows that > ? vecsort(v, (x,y)->abs(x)-abs(y)) > would work equally well. > So I wonder why enveloping the cmpf function with sign() is "very useful" > and why? This is historical: a long time ago, the comparison function was required to return 1, 0 or -1. The sign function is now useless for vecsort, I have updated the documentation. > Also, the build-in help for vecsort() says: > "If cmpf is an integer, sort according to the value of the k-th component > of each entry." > First, it's not clear what is k here. Perhaps, it should say "if cmpf > equals an integer *k*" or something like that. Done ! In fact, this is a rather useless construct since it's trivial to emulate it with (x,y)->x[k]-y[k]. A much more useful one is k = [1,3,2] (sort by 1st entry, then 3rd, then 2nd: this one is more painful to emulate with a closure...). > Second, my first thought was that I can use vecsort() to sort a vector of t_ > INTMOD based on the value of moduli. Indeed, the modulus of t_INTMOD x > equals component(x,1), so supposedly > ? vecsort([Mod(2,3),Mod(1,2)],1) > should work, but it does not. Indeed, "component" is a bad choice of words given the existence of component(). The function is specific to t_VEC (and t_COL) entries. You can use vecsort(v, (x,y)->component(x,1)-component(y,1)) or vecsort(v, (x,y)->x.mod-y.mod) explicitly, of course. I would myself use the second one, even if component(x,1) was implied by the "k = 1" construct. > So, I wonder if vecsort() can be easily extended to sort objects on any > types based on the value of component(x,k) (for a given cmpf=k) or it's > very specific to vectors and cannot be extended to other types. It's easy to do, I'm not sure how useful it would be. I would find it confusing given that the meaning of "component(x)" depends very much on the type of x: an explicit comparison function seems best when a non-trivial component is implied. Cheers, K.B. -- Karim Belabas, IMB (UMR 5251) Tel: (+33) (0)5 40 00 26 17 Universite de Bordeaux Fax: (+33) (0)5 40 00 21 23 351, cours de la Liberation http://www.math.u-bordeaux.fr/~kbelabas/ F-33405 Talence (France) http://pari.math.u-bordeaux.fr/ [PARI/GP] `