質問

私は衛生を学んでおり、Schemeで簡単なforループを作成しようとしました。以下の例に示すように、3種類の構造をサポートしたい

(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)]))
役に立ちましたか?

解決

ここでは繰り返しはあまり見ません。一つだけです。そのようにして削除できます:

(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)]))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top