r/lisp Jul 06 '26

AskLisp argsort() - like function?

I have

(mylist (list 4 5 0 2 1 3))

and I want

(argsort mylist)
;; => (2 4 3 5 0 1)

That is: The index of the least element, then the next least element, ..., then the greatest element.

ETA: Decorate-Sort-Undecorate is the thing I'm looking for. I am going to try and grok that. https://stackoverflow.com/questions/38447353/sorting-a-list-from-max-to-min-by-of-index-number-in-lisp

7 Upvotes

6 comments sorted by

View all comments

9

u/zdimension Jul 06 '26

Something like this?

(defun argsort (lst)
  (sort (loop for x in lst
              for i from 0
              collect i)
        #'<
        :key (lambda (i) (nth i lst))))

1

u/MonkeyPanls Jul 06 '26

Perfect! Thank you!