【问题标题】:Why does my function keep returning an empty list?为什么我的函数总是返回一个空列表?
【发布时间】:2019-06-27 12:26:49
【问题描述】:

我正在 Racket 中编写一个upper-threshold 函数,它接受两个参数:一个数字列表和一个整数。

它所要做的就是递归地遍历列表并返回低于给定整数值的整数列表。但是,我的函数总是吐出一个空列表。我觉得这与我使用 append 函数的方式有关。

我已经显示了应该附加到我的空列表 z 的值,它们是正确的,但是由于某种原因它们没有附加到列表中!

(define (upper-threshold x y [z '()])
  (cond [(null? x) z]
    [else (cond [(< (first x) y) (append (list (first x)) z) (upper-threshold (rest x) y)]
          [else (upper-threshold (rest x) y)])]))

例如,调用和返回应该如下所示:

(upper-threshold '(1 2 3 5 6) 4) '(1 2 3)

【问题讨论】:

    标签: racket


    【解决方案1】:

    您没有在对upper-threshold 的任何递归调用中包含第三个参数z。这意味着在每次迭代中,z 将始终是空列表。此外,Racket 的append 不会改变它所操作的列表。这意味着表达式 (append (list (first x)) z) 会生成一个全新的列表,而不是更改 xz

    (cond [(< (first x) y)
           (append (list (first x)) z) ; produces a new list which is not used, x and z
                                       ; remain unchanged
           (upper-threshold (rest x) y ; no z argument passed in here, defaults to '()
           )]
          [else
           (upper-threshold (rest x) y ; no z argument passed in here, defaults to '()
           )])
    

    我们需要做的就是为每个递归调用提供正确的第三个参数。

    (cond [(< (first x) y)
           (define new-z (append (list (first x)) z))
           (upper-threshold (rest x) y new-z)]
          [else
           (upper-threshold (rest x) y z)])
    

    另外:当您想在列表的前面添加一个元素时,使用函数cons 而不是append 会更容易。因此,(append (list (first x)) z) 变为 (cons (first x) z)

    (cond [(< (first x) y)
           (define new-z (cons (first x) z))
           (upper-threshold (rest x) y new-z)]
          [else
           (upper-threshold (rest x) y z)])
    

    【讨论】:

    • 啊,我明白了。我对 append 函数如何与参数的递归调用一起工作感到非常困惑。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    • 1970-01-01
    • 2021-05-24
    • 2013-01-09
    • 1970-01-01
    相关资源
    最近更新 更多