gpt4 book ai didi

functional-programming - 请在 Scheme 中重构我的宏

转载 作者:行者123 更新时间:2023-12-04 08:40:42 25 4
gpt4 key购买 nike

我正在学习卫生,我试图在 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)]))

最佳答案

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

(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)]))

关于functional-programming - 请在 Scheme 中重构我的宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1817038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com