Skip to content

Instantly share code, notes, and snippets.

@lispm
Created July 14, 2016 16:24
Show Gist options
  • Save lispm/b1e1da1b7df2f53bfc9a52511cc4c025 to your computer and use it in GitHub Desktop.
Save lispm/b1e1da1b7df2f53bfc9a52511cc4c025 to your computer and use it in GitHub Desktop.
find the minimum item in a list, using a key to extract a value to minimize
(defun minimize (list &key (pred #'<) (key #'identity))
"returns values: the minimum value and if there was one"
(if (null list)
(values nil nil)
(values (loop with min-e = (first list)
with min-v = (funcall key min-e)
initially (pop list)
for e in list
for v = (funcall key e)
if (funcall pred v min-v) do (setf min-e e min-v v)
finally (return min-e))
t)))
CL-USER 35 > (minimize '((5 . a) (3 . b) (1 . c) (9 . d)) :key #'car)
(1 . C)
T
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment