Sujet : Re: finding the min or max element of a list
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 29. Jun 2025, 00:55:36
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <103pvdl$150ok$1@dont-email.me>
User-Agent : XanaNews/1.18.1.6
(defun best (lst cmp &key (key #'identity))
(loop with rtn = (car lst)
for x in (cdr lst)
when (funcall cmp (funcall key x) (funcall key rtn))
do (setq rtn x)
finally (return rtn)))
If one uses a Lispy language, then instead of using
a macro whose source measures 60 kilobytes, he can
simply use the function "reduce".
Gauche Scheme
(define (best lst cmp :key (key identity))
(reduce
(lambda (x chosen)
(if (cmp (key x) (key chosen)) x chosen))
#f
lst))
(best '((a) (f o o b) (b a r) (2 3)) > :key length)
===>
(f o o b)
(best '(5 0 4 9) >)
===>
9
(best '(5 0 4 9) <)
===>
0
(best '() >)
===>
#f
(best '(2) >)
===>
2