简体   繁体   English

球拍附加了不希望的列表反转

[英]Racket Append Undesired Reversal of List

I wrote a small function that takes a list and returns a list composed of only positive numbers. 我编写了一个小函数,该函数接受一个列表并返回仅包含正数的列表。 This all works fine, but for some reason, it is reversing the order. 一切正常,但由于某种原因,它使顺序相反。 More information below on that. 下面的更多信息。 Could someone please tell me if this is normal, or if I miss-wrote something? 有人可以告诉我这是否正常,或者我写错了什么吗? Thank you in advance. 先感谢您。

(define (positive-nums-only lst)
  (if (empty? lst)
      '()
      (append (positive-nums-only (cdr lst))
              (if (>= (car lst) 0)
                  (list (car lst))
                  '()))))
(positive-nums-only '(1 2 -4 90 -4))

The above test case returns '(90 2 1) 上面的测试用例返回'(90 2 1)

You did not make a mistake, the program is making what you asked. 您没有记错,程序正在按照您的要求进行。

See, the program finishes the recursion calls first, before going into resolving the if statement. 可以看到,在解析if语句之前,程序首先完成了递归调用。 This causes the (list ... ) to start listing from the last element that is positive, in this example it will be 90 . 这将导致(list ... )从最后一个为正的元素开始列出,在此示例中为90

Changing the code order will produce the result you want. 更改代码顺序将产生所需的结果。

(define (positive-nums-only lst)
(if (empty? lst) '()
  (append (if (>= (car lst) 0 )
             (list (car lst))
             '())
          (positive-nums-only (cdr lst)))
)
)

On the other hand, this kind of recursion could be expensive to the computer. 另一方面,这种递归对于计算机可能是昂贵的。 I'd use tail recursion, like this: 我将使用尾递归,如下所示:

  (define positive-nums-only-tail
  (λ (lst r)
    (cond ((empty? lst) (reverse r))
          ((positive? (car lst))
           (positive-nums-only-tail (cdr lst)
                                    (cons (car lst) r)))
          (else (positive-nums-only-tail (cdr lst) r))
          )
    )
  )

Have you tried reversing the append? 您是否尝试过反转附件?

(define (positive-nums-only lst)
  (if (empty? lst)
      '()
      (append (if (>= (car lst) 0) (list (car lst)) '())
              (positive-nums-only (cdr lst)))))

Personally I find it more natural to write it like this: 我个人觉得这样写更自然:

(define (positive-nums-only lst)
  (if (empty? lst)
      '()
      (let ((rest (positive-nums-only (cdr lst))))
        (if (>= (car lst) 0)
            (cons (car lst) rest)
            rest))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM