문제

나는 위생을 배우고 있으며 체계에서 루프를 간단하게 만들려고 노력했습니다. 아래의 예에서 볼 수 있듯이 세 가지 종류의 구성을 지원하고 싶습니다.

(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