Functions on generic sequences
From: Dave Roberts (ldave-re-move_at_re-move.droberts.com)
Date: 10/26/04
- Next message: Kenny Tilton: "Re: Functions on generic sequences"
- Previous message: Frank Buss: "Re: Challenge: Triangles puzzle"
- Next in thread: Kenny Tilton: "Re: Functions on generic sequences"
- Reply: Kenny Tilton: "Re: Functions on generic sequences"
- Reply: David Sletten: "Re: Functions on generic sequences"
- Reply: Szymon: "Re: Functions on generic sequences"
- Reply: Rahul Jain: "Re: Functions on generic sequences"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 26 Oct 2004 06:00:40 GMT
So I wanted to write a function that would average the numbers in a
sequence: either a list or an array. My first attempt was quite lame, but
functional:
(defun average (sequence &key (key #'identity))
;;; WARNING: Sloppy code. Could compute len and sum at same time
(let ((len (length sequence))
(sum (reduce #'+ sequence :key key)))
(/ sum len)))
This is obviously slower than need be for a number of reasons. The most
obvious is that for lists, it traverses things twice, once to find the
length and then again to create the sum.
I then decided to specialize things a bit and arrived at:
(defun fast-average (sequence &key (key #'identity))
(etypecase sequence
(list (loop for x in sequence
count x into length
sum (funcall key x) into sum
finally (return (/ sum length))))
(vector (loop for x across sequence
sum (funcall key x) into sum
finally (return (/ sum (length sequence)))))))
Now, this works well: the runtime on a long list is about half that of the
first version, which is what you would expect if you only traverse the list
once, not twice.
The main problem is that it seems so bifurcated. By that I mean that the
first version seems to really operate on sequences while the second is
obviously two routines, each specialized on a data type.
Is there anyway to sort of harmonize these two, giving some that has better
runtime but yet doesn't get totally data-type specific?
-- Dave Roberts, ldave-re-move@re-move.droberts.com Slowly but surely, the programming world is finding Lisp... http://www.findinglisp.com/blog/
- Next message: Kenny Tilton: "Re: Functions on generic sequences"
- Previous message: Frank Buss: "Re: Challenge: Triangles puzzle"
- Next in thread: Kenny Tilton: "Re: Functions on generic sequences"
- Reply: Kenny Tilton: "Re: Functions on generic sequences"
- Reply: David Sletten: "Re: Functions on generic sequences"
- Reply: Szymon: "Re: Functions on generic sequences"
- Reply: Rahul Jain: "Re: Functions on generic sequences"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|