[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Missing and desired sequence function.



I would like a sequence function that gives me the "best" element of a
sequence.  I want to give it a sequence, a predicate and (with keywords)
the bounds of the sequence and a key to extract the arguments for the
predicate.  It returns the element of the sequence that is "predicate"
(e.g., less than) all the other elements.  There are a couple ways to
implement this using existing functions, but it would be nice if CLtL
had this as part of the language if others find it a sibling of existing
functions.

Implementation 1: User SORT.  Running time is n*log(n).  Sort the list
and return the first element.  Guarenteed to cons.  This fails for zero
length sequences. Zero length sequences may want to be or signal an
error.

	(defun best (sequence predicate &key key start end)
	  (elt (sort (subseq sequence start end) predicate :key key)
	       0))

Implementation 2: Use REDUCE.  Running time is linear.  Make a reduction
function which compares two elements and returns the best.

	(defun best (sequence predicate &key key start end)
	  (reduce #'(lambda (elt1 elt2)
		      (if (funcall predicate
				   (funcall key elt1)
				   (funcall key elt2))
			  elt1
			  elt2))
		  sequence
		  :start start
		  :end end))

There are obviously some details missing in the above implementations;
they are to convey the concept.  A better name might be CHOOSE.

Does this seem reasonably useful to add to the language?