.Re: #'reduce

6 views
Skip to first unread message

Robert L.

unread,
Mar 26, 2022, 6:09:36 PMMar 26
to
> >> (reduce #'max '("This" "is" "a" "test" ".") :key #'length)
> >>
> >
> >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.
> >
> >Instead of REDUCE, try the following:
> >
> >(APPLY #'MAX (MAPCAR #'LENGTH '("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)
> >
>
> Macintosh Common Lisp (MCL) accepts the :key keyword parameter:
> ? (reduce #'max '("This" "is" "a" "test" ".") :key #'length)
> 4
>
> You can also use loop to make it clearer:
> ? (loop for el in '("This" "is" "a" "test" ".")
> maximizing (length el))
> 4

Gauche Scheme:

(use gauche.lazy) ;; For lmap.

(fold max 0 (lmap string-length '("is" "a" "test")))

===>
4
Reply all
Reply to author
Forward
0 new messages