Discussion of Common Lisp
-
Warren Wilkinson
- Posts: 117
- Joined: Tue Aug 10, 2010 11:24 pm
- Location: Calgary, Alberta
-
Contact:
Post
by Warren Wilkinson » Wed Sep 01, 2010 1:13 pm
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)))
-
edgar-rft
- Posts: 226
- Joined: Fri Aug 06, 2010 6:34 am
- Location: Germany
Post
by edgar-rft » Thu Sep 02, 2010 3:03 am
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.
-
Warren Wilkinson
- Posts: 117
- Joined: Tue Aug 10, 2010 11:24 pm
- Location: Calgary, Alberta
-
Contact:
Post
by Warren Wilkinson » Thu Sep 02, 2010 9:21 am
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.