Hi Tomas,

> the 'sort' function has the less-than relation built-in.  Is there an
> "easy" way of sorting a list using a user-defined less-than relation?

Well, in a certain way you used it already, with 'by'.


I'm not quite sure about the purpose of

>                (when (apply Lt NIL X Y)

'apply' does not make much sense here, as the list argument is NIL. I
think that

   (when (Lt X Y)

would do directly what you intend.


However, there is another problem with 'order', probably just a wrong
parenthesis:

>          (let S 0
>             (for Y Lst
>                (when (apply Lt NIL X Y)
>                   (inc 'S) ) ) )
>          (push 'Q (cons S X)) )

'S' is unbound when 'cons' is called, so the CARs of all elements end up
with NIL (or whatever 'S' was before).


> That is quite simple but not efficient.

True, as the list is iterated proportional to the square of the length.
Why do you think this is necessary?


> Could the existing 'sort' function be extended for the scenario with a
> user-defined less-than relation?

I decided back then to write 'sort' without a functional argument, as I
believe that it is more efficient this way. If 'sort' calls a function
twice each time two elements need to be compared, it will involve more
overhead than simply applying this function once to each argument before
the call to 'sort'. 'sort' is much simpler this way and does not have to
do any bookkeeping. Built-in list functions can be used better and more
efficiently to do the pre- and post-processing.

'by' already does something similar what you did in 'order'. Let's say

   : (by - sort (6 2 4 7 4 1 3 7 5))
   -> (7 7 6 5 4 4 3 2 1)

then 'by' first builds a list

   ((-6 . 6) (-2 . 2) (-4 . 4) (-7 . 7) (-4 . 4) (-1 . 1) (-3 . 3) (-7 . 7) (-5 
. 5))

This is handed to 'sort', which gives

   ((-7 . 7) (-7 . 7) (-6 . 6) (-5 . 5) (-4 . 4) (-4 . 4) (-3 . 3) (-2 . 2) (-1 
. 1))

Then 'by' extracts the CDRs.

Of course, the same thing can be achieved even more efficiently with

   : (flip (sort (6 2 4 7 4 1 3 7 5)))
   -> (7 7 6 5 4 4 3 2 1)


What user-defined less-than relation do you have in mind?

Cheers,
- Alex
-- 
UNSUBSCRIBE: mailto:[email protected]?subject=unsubscribe

Reply via email to