Created
December 22, 2011 15:19
-
-
Save cqfd/1510663 to your computer and use it in GitHub Desktop.
Adding Python/Clojure-style list comprehensions to Common Lisp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Beginner's attempt at adding list comprehensions to Common Lisp. | |
;; Examples: | |
;; (for ((x '(1 2 3))) (* x x)) # => (1 4 9) | |
;; (for ((x '(1 2)) (y '(a b))) (list x y)) # => ((1 a) (1 b) (2 a) (2 b)) | |
(defun foldr (f z xs) | |
(cond ((null xs) z) | |
(t (funcall f (car xs) (foldr f z (cdr xs)))))) | |
;; Works by nesting calls to dolist. The dolists push each evaluation of | |
;; the macro's body parameter onto an accumulator, which is then | |
;; reversed in the ultimate expansion. | |
(defmacro for (bindings body) | |
(let ((acc (gensym))) | |
(cond ((null bindings) (error "needs at least one binding!")) | |
(t (let ((expansion | |
(foldr (lambda (b expr) | |
`(dolist ,b ,expr)) | |
`(push ,body ,acc) | |
bindings))) | |
`(let ((,acc nil)) | |
,expansion | |
(nreverse ,acc))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I know it's an exercise in learning, but
loop
already does way more than anyone could possibly even want to do.