【问题标题】:Make my own while loop using "define-syntax-rule"使用“define-syntax-rule”制作我自己的 while 循环
【发布时间】:2023-04-08 07:59:01
【问题描述】:

我正在尝试使用“定义语法规则”在球拍中创建自己的 while 循环。 我希望它是基于程序的,所以没有辅助函数(即只使用 lambda、let、letrec 等)。

我有这个,但它给了我某种 lambda 标识符错误。

(define-syntax-rule (while condition body)
  (lambda (iterate)
    (lambda (condition body) ( (if condition)
                                   body
                                   iterate))))

我想要它这样我就可以像普通的 while 循环一样使用它 例如:

(while (x < 10) (+ x 1))

在循环完成后调用它会(应该)返回 10。

如何修复我的代码以执行此操作?

【问题讨论】:

  • 您想要的语法实际上没有任何意义,原因有几个。首先(x &lt; 10)没有意义,因为Scheme使用前缀函数应用,所以它必须是(&lt; x 10)。其次,x 绑定在哪里?您当前的代码并不清楚。第三,(+ x 1) 不会改变 x,它只会产生一个新数字,就像 x + 1 在类 C 语言中所做的那样。您需要执行(set! x (+ x 1)) 来模拟x += 1。如果没有这些说明,即使使用您尝试的代码示例,也很难回答您的问题。
  • 也许你应该看看 SRFI-42 "Eager Comprehensions" 的实现。

标签: while-loop scheme lisp racket define-syntax


【解决方案1】:

这是我的Standard Prelude 中的while,以及它的使用示例:

Petite Chez Scheme Version 8.4
Copyright (c) 1985-2011 Cadence Research Systems

> (define-syntax while
    (syntax-rules ()
      ((while pred? body ...)
        (do () ((not pred?)) body ...))))
> (let ((x 4))
    (while (< x 10)
      (set! x (+ x 1)))
    x)
10

你可能应该和你的导师谈谈你对 Scheme 的误解。

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多