• Re: finding the min or max element of a list

    From B. Pym@Nobody447095@here-nor-there.org to comp.lang.lisp on Sat Jun 28 23:55:36 2025
    From Newsgroup: comp.lang.lisp

    (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
    --- Synchronet 3.21d-Linux NewsLink 1.2