Reading the Python code of Collective intelligence you see a lot of list comprehension code in it. In Scheme you don't have list comprehension at all. So you are screwed you might think.
Not at all. In fact, it is quite easy to add list comprehension to the language. You even don't need to go through a PEP process, JSR specification or wait for Ruby to include it.
You have Scheme macros at your disposition. Note that you already have SRFI-42 which provides all you need. Here we will implement our own system just to show how nice and simple it is to extend the Scheme language with a new syntax construct.
The implementation is based on Implementation of a Lisp comprehension macro from Guy Lapalme.
First let see how a Python expression is translated:
[e for e in [1,2,3,4,5,6,7,8,9,0] if e % 2 == 0]The equivalent Scheme code is:
(:ec e (e <- '(1 2 3 4 4 5 6 7 8 9 0)) (= 0 (modulo e 2)))
To be able to run this code you need the following definitions:
(define-syntax :ec-aux
(syntax-rules (<-)
((:ec-aux (?exp) ?list)
(cons ?exp ?list)) ;; rule A
((:ec-aux (?exp (?v <- ?l1) . ?rest) ?l2)
(letrec ((h (lambda (us)
(if (null? us)
?l2
(let ((?v (car us))
(us* (cdr us)))
(:ec-aux (?exp . ?rest) (h us*)))))))
(h ?l1)))
((:ec-aux (?exp ?pred . ?rest) ?list)
(if ?pred (:ec-aux (?exp . ?rest) ?list) ?list))))
(define-syntax :ec
(syntax-rules ()
((:ec . ?term) (:ec-aux ?term '()))))
It is remarkable how you can implement such a feature in 19 lines of code. I wonder how long the implementation is in the C Python implementation.