【问题标题】:Writing recursive enumeration function in Scheme在 Scheme 中编写递归枚举函数
【发布时间】:2011-08-27 00:24:32
【问题描述】:

我正在编写一个递归枚举函数,但我在某处遇到了一个简单的错误。

这是应该发生的:

(enum 1 0.5 2.5)  
> (1.0 1.5 2.0 2.5)

代码如下:

(define enum
   (lambda (start step stop)
      (if (not (<= stop start))
          (cons start (enum (+ start step) step  stop))
          ('(stop))
          )))

编辑:
我得到的错误(来自 Impromptu (http://impromptu.moso.com.au/))是:

> (print (enum 0 0.5 2.5))  
:ERROR: position:(0) in function "enum"  
illegal function  
Trace: enum  

【问题讨论】:

  • 你遇到了什么错误?

标签: algorithm recursion scheme lisp enumeration


【解决方案1】:

我相信你的问题出在这条线上

('(stop))

我认为您的想法是正确的,即您想在到达终点后停止执行递归,但这不是这样做的方法。因为您已将它放在双括号中,所以它被解释为“评估'停止',然后尝试将其作为函数调用”。但是,stop 不是函数,因此会出现错误。

要解决此问题,如果您想将返回值设为仅包含 stop 的列表,请使用 list 函数:

(define enum
   (lambda (start step stop)
      (if (not (<= stop start))
          (cons start (enum (+ start step) step  stop))
          (list stop)
          )))

请注意,list stop 周围只有一组括号。

希望这会有所帮助!

【讨论】:

  • 当我说 ('(stop)) 时,我指的是一个列表,其中包含一个元素:“stop”参数 (== 2.5)。这就是为什么我说“
  • @amindfv- 我发现了问题并更新了这个答案 - 你试图通过添加额外的括号来评估 stop 作为一个函数。我已经更新了我的答案以反映这一点;你能再看一遍,看看它是否更准确地解释了你的错误?
  • 谢谢;这正是我想要的。
  • @amindfv:你也可以使用quasiquote语法:`(,stop),虽然(list stop)更清晰。
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-10-20
相关资源
最近更新 更多