【问题标题】:How do I get rid of the #<void> that results from this recursive Scheme function?如何摆脱此递归 Scheme 函数产生的 #<void> ?
【发布时间】:2013-10-12 20:27:48
【问题描述】:

我应该编写一个递归函数,将另一个函数应用于一组连续整数并返回一个列表。如果 start 大于 stop,我应该返回一个空集。

这就是我所拥有的。我不确定这是解决问题的最佳方法,但是...

(define (myfunction start stop fn)
  (if (<= start stop)
      (cons (fn start)(myfunction (+ start 1) stop fn)))
 )

(define (foo val1) ; just to demonstrate myfunction
  (* val1 2))

当我尝试在方案解释器中使用它时,我得到了这个:

(myfunction 0 5 foo)
(0 2 4 6 8 10 . #<void>)

我能做些什么来摆脱空虚的东西?我有点困惑。

【问题讨论】:

    标签: recursion scheme


    【解决方案1】:

    考虑如果你这样做会发生什么:

    > (list (if #f 'then-value))
    ;=> (#<void>)
    

    您的函数有一个 if 没有“else”部分。

    (define (myfunction start stop fn)
      (if (<= start stop)
          (cons (fn start)
                (myfunction (+ start 1) stop fn))
          ; missing something here
     ))
    

    如果不是(&lt;= start stop),那么列表应该是什么?我猜想一个合理的默认值是空列表,因此当最终使用 startstop 的值调用 (myfunction (+ start 1) stop fn) 使得 start 大于 stop 时,你会得到空列表,因此(cons (fn start) (myfunction ...)) 有一个空列表作为其第二个参数:

    (define (myfunction start stop fn)
      (if (<= start stop)
          (cons (fn start)
                (myfunction (+ start 1) stop fn))
          '()))
    
    (myfunction 0 5 (lambda (x) (* x 2)))
    ;=> (0 2 4 6 8 10)
    

    有关输出为何为 (&lt;elements&gt; . #&lt;void&gt;) 的更多信息(即为什么它的末尾有点),请查看this answer(免责声明:这是我的回答)Recursive range in Lisp adds a period?

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 2021-09-28
      • 2016-07-19
      • 1970-01-01
      相关资源
      最近更新 更多