From: John Robert Leavitt
Subject: Re: #'reduce
Date: 
Message-ID: <oeoSsDW00WB50B1mVA@andrew.cmu.edu>
Danny Brewer (·····@farallon.com) says:
>In article <················@milan.ims.uni-stuttgart.de>,
>···@milan.ims.uni-stuttgart.de (Oliver Christ) wrote:
>> this might be an annoying question, but why does
>>
>>  (reduce #'max '("This" "is" "a" "test" ".") :key #'length)
>>
>> result in a 'unknown keyword: :key' error both with Allegro CL 4.1 and
>> Lucid 4.0 on a Sparc?
>
>Reduce doesn't accept :KEY according to CLtL2.  In fact, if you
>look at REDUCE more closely, you'll see that :KEY wouldn't make sense.

agreed.

>Instead of REDUCE, try the following:
>
>(APPLY #'MAX (MAPCAR #'LENGTH '("This" "is" "a" "test" ".")))

Actually, it looked like what Oliver really wanted was something that
would yield the longest string, not just its length.  So, somthing
like this should do nicely:

(reduce #'(lambda (a b)
            (if (> (length a) (length b))
                a
                b))
        '("this" "is" "a" "test" "."))

>Even more efficient would be:
>
>(LET ((max 0))
>  (DOLIST (elt '("This" "is" "a" "test" "."))
>    (SETF max (MAX max (LENGTH elt))))
>  max)
Or rather:

(let ((result nil))
  (dolist (elt '("this" "is" "a" "test" "."))
    (if (> (length elt) (length result))
        (setf result elt)))
  result)

Cheers,

John.

-John R. R. Leavitt-----------------------------------------------------------
-Center for Machine Translation                                  412/268-2292-
-Carnegie Mellon University                                   ····@cs.cmu.edu-
------------------------------------------------------------------------------