emacs-devel
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: master 4b79c80c999 1/2: New function 'sort-on'


From: Michael Heerdegen
Subject: Re: master 4b79c80c999 1/2: New function 'sort-on'
Date: Wed, 06 Mar 2024 04:20:40 +0100
User-agent: Gnus/5.13 (Gnus v5.13)

Eli Zaretskii <eliz@gnu.org> writes:

> Any way you can think of rewriting this so that it's easier to read
> and understand, i.e. with less macrology?

To make the code readable on wants to factor out the operation of
replacing the list elements destructively, because that is done multiple
times and the main aspect.  The standard way would be to use helper
functions, but that would make the code less efficient due to lambdas,
or require several top-level definitions, which would be nonsense for
such a small defun.  So I did the factoring using a local macro.

The expanded definition would look like this:

#+begin_src emacs-lisp
(defun sort-on (sequence predicate accessor)
  (let* ((l (sort
             (let ((ret sequence))
               (while sequence
                 (setcar sequence
                         (let* ((elt (car sequence)))
                           (cons elt (funcall accessor elt))))
                 (setq sequence (cdr sequence)))
               ret)
             #'(lambda (x y) (funcall predicate (cdr x) (cdr y)))))
         (ret l))
    (while l
      (setcar l (let* ((elt (car l))) (car elt))) (setq l (cdr l)))
    ret))
#+end_src

You would prefer that?  But now the operations on the list elements are
spread over all the code.  Not a good style.  It depends on the reader
which version is easier to understand, but from all I learned about
coding the macro-based version is better and easier to understand.

To make my sort predicate building code as efficient as possible (as had
been requested), I will also have to rely on some form of code rewriting
like this.


And Dmitry Gutov <dmitry@gutov.dev> wrote:

> But if we're going to merge this functionality into the core 'sort',
> then I guess the new code would have to move to src/fns.c, and it
> might be difficult to use macros there.

Anyone please feel free to do this.  Might be better to simply code this
in C.

Michael.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]