簡體   English   中英

球拍定義列表

[英]Racket define list

我必須使用語言球拍解決嵌套任務。 根據給定的列表,我必須創建僅包含除以 10 沒有剩余的元素的新列表。

到目前為止我的代碼:

(define (brel x sp)
   (cond ((null? sp) 0)
         (( = (remainder (car sp) 10) 0) (car sp))
         (else (brel x (cdr sp)))))

(define (spbr L)
  (define (f l1)
    (if (null? l1) '()
     (cons (brel (car l1) L) (f (cdr l1)))))
 (f L))
(spbr (list 50 5 3))

給代碼當前計算第一個列表中元素的每個重復並將它們添加到新列表中。 我必須改變什么才能使它工作?

您不需要幫助程序,只需構建一個僅包含滿足條件的項目的新列表:

(define (spbr L)
  (cond ((null? L) '())
        ((= (remainder (car L) 10) 0)
         (cons (car L) (spbr (cdr L))))
        (else
         (spbr (cdr L)))))

使用filter程序會更慣用:

(define (spbr L)
  (filter (lambda (e) (zero? (remainder e 10)))
          L))

無論哪種方式,它都按預期工作:

(spbr '(50 5 3 70))
=> '(50 70)

暫無
暫無

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

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