Skip to content

Instantly share code, notes, and snippets.

@cqfd
Created December 22, 2011 15:19
Show Gist options
  • Save cqfd/1510663 to your computer and use it in GitHub Desktop.
Save cqfd/1510663 to your computer and use it in GitHub Desktop.
Adding Python/Clojure-style list comprehensions to Common Lisp
;; 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)))))))
@apg
Copy link

apg commented Nov 10, 2012

I know it's an exercise in learning, but loop already does way more than anyone could possibly even want to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment