Created
July 14, 2016 16:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (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