簡體   English   中英

在 Dr. Racket 中,如何以相反的順序顯示列表中的 2 個元素?

[英]In Dr. Racket, how would I display the 2 elements in a list in the opposite order?

我想編寫一個函數,以相反的順序在列表中顯示 2 個元素。 到目前為止,這是我的代碼:

(define (reverse-order list)
  (cons (rest list) (cons (first list) empty)))

出於某種原因,此代碼不起作用:例如:如果我輸入

 (reverse-order (cons 1 (cons 2 empty))) 

我想要的輸出是

(cons 2 (cons 1 empty))

然而,相反,我得到

(cons (cons 2 empty) (cons 1 empty))

有關如何解決此代碼的任何提示都將非常有幫助。

那是因為您要獲取列表的rest ,即'(2) ,而不是第二個元素2 並且您不應該調用與同名內置過程沖突的參數list 試試這個:

(define (reverse-order lst)
  (cons (second lst)
        (cons (first lst)
              empty)))

或者更簡單,現在您明白為什么調用參數list是個壞主意:

(define (reverse-order lst)
  (list (second lst) (first lst)))

或者只是使用內置的reverse程序:)

(define reverse-order reverse)

無論如何,它按預期工作:

(reverse-order '(1 2))
=> '(2 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM