3

我正在学习卫生,我尝试在 Scheme 中创建一个简单的 for 循环。我想支持三种结构,如下例所示

(for i = 1 : (< i 4) : (++ i)
  (printf "Multiplication Table for ~s\n" i)
  (for j = 1 to 5
    (printf "~s * ~s = ~s\n" i j (* i j))))

我还想支持带有这样的过滤器的循环:

(for k = 1 : 10 : (list even? (λ(x) (> x 4))) : (++ k)
  (print k))

我有这个,但我可以看到很多重复。请帮我删除冗余。

(define-syntax for
  (syntax-rules (= to :)
    [(for x = initial : final : conditions : increment body ...)
     (letrec ([loop (λ(x)
                      (when (<= x final)
                        (when (andmap (λ(condition) (condition x)) conditions)
                          body ...)
                        (loop increment)))])
       (loop initial))]
    [(for x = initial : condition : increment body ...)
     (letrec ([loop (λ(x)
                      (when condition
                        body ...
                        (loop increment)))])
       (loop initial))]
    [(for x = initial to n body)
     (for x = initial : (<= x n) : (+ x 1) body)]))
4

1 回答 1

7

我在这里没有看到很多重复。只有一个。可以这样删除:

(define-syntax for
  (syntax-rules (= to :)
    [(for x = initial : final : conditions : increment body ...)
     (for x = initial : (<= x final): increment
          (when (andmap (λ(condition) (condition x)) conditions)
            body ...))]
    [(for x = initial : condition : increment body ...)
     (letrec ([loop (λ(x)
                      (when condition
                        body ...
                        (loop increment)))])
       (loop initial))]
    [(for x = initial to n body)
     (for x = initial : (<= x n) : (+ x 1) body)]))
于 2009-11-30T10:29:44.303 回答