Page 2 of 2
Re: averaging
Posted: Wed Sep 01, 2010 1:13 pm
by Warren Wilkinson
edgar-rft wrote:Now here is a working 'reduce' example:
Code: Select all
(defun average (lst)
(/ (reduce #'+ lst :key #'(lambda (x) (first (last x))))
(length lst)))
The :key argument tells 'reduce' to which element from the lists inside 'lst' the '+' function shall be applied. Because 'last' returns the last element as a list, the element itself must be extracted with 'first'...
Isn't #'(lambda (x) (first (last x))) the same as #'second in this case?
Code: Select all
(defun avg (lst) (/ (reduce #'+ lst :key #'second) (length lst)))
Re: averaging
Posted: Thu Sep 02, 2010 3:03 am
by edgar-rft
Warren Wilkinson wrote:Isn't #'(lambda (x) (first (last x))) the same as #'second in this case?
Yes, it is.
I'm used to search rather huge trees, so seeing something at the end of a list automatically makes me write (first (last x))...
The #'second solution in this case is clearly better, because no lambda construct is needed at all.
Re: averaging
Posted: Thu Sep 02, 2010 9:21 am
by Warren Wilkinson
Yeah, I use that too --- Its often inconvenient that last returns a list rather than an item. Maybe I'll just define a utility function
Code: Select all
(defun last-item (list) (car (last list)))
and be done with it.