[alexandria-devel] reductions
Cyrus Harmon
ch-lisp at bobobeach.com
Thu Dec 30 07:56:16 UTC 2010
Hi Alexandrians,
Clojure has a function that I occasionally find useful, reductions. It's like reduce, only it returns not the last value of calling the two-arg function, but a list consisting of the first element of the input sequence, followed by the result of calling the two-arg with the first and second elements of the input sequence, then the result of calling the two-arg function with the previous result and the third element, and so on... e.g.:
CL-USER> (reductions #'+ '(1 2 3 4))
(1 3 6 10)
Here's the code. There are probably better ways to do this, but this is at least portable and simple. I think this would be a useful addition to alexandria.
(defun reductions (function sequence &rest args)
(let ((l (list (first sequence))))
(apply #'reduce
(lambda (a b)
(let ((val (funcall function a b)))
(push val l)
val))
sequence
args)
(nreverse l)))
thanks,
Cyrus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/alexandria-devel/attachments/20101230/cc491ce5/attachment.html>
More information about the alexandria-devel
mailing list