Cool listcomp, revisited

About two weeks ago I looked at a list comprehension in Haskell and Python. Since then I have also looked at eager comprehensions in Scheme (using SRFI-42). So, I just thought I'd be interesting to write that same listcomp in Scheme. Here it is...

(use syntax-case)
(use srfi-42)

(define (f n)
  (list-ec (: x 1 (+ n 1))
           (: y (+ x 1) (+ n 1))
           (: z (+ y 1) (+ n 1))
           (if (= (+ (* x x) (* y y))
                  (* z z)))
           (list x y z)))

(print (f 20))

From a readability point of view, this code might benefit from something like

  (let ((m (+ n 1)))
      (list-ec (: x 1 m)
               (: y (+ x 1) m)
               (: z (+ y 1) m)
               ...

as the ranges used by eager comprehensions don't include the upper bound, much like Python's range function. (I.e. (: x 10) includes the numbers 0 through 9, but not 10.)

Leave a Comment