请在Scheme中重构我的宏
我正在学习卫生,我尝试在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)]))
I am learning hygiene and I tried to make a simple for loop in Scheme. I want to support three kinds of constructs as shown in example below
(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))))
I want to also support for loops with filters like this:
(for k = 1 : 10 : (list even? (λ(x) (> x 4))) : (++ k)
(print k))
I have this but I can see a lot of repetition. Please help me remove redundancies.
(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)]))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里没有看到太多重复。只有一个。可以这样删除:
I don't see a lot of repetition here. Just one. It can be removed that way: