我要回答與評論的例子你的問題希望你能真正學到一些東西,而不是僅僅給出可行的代碼。實際上,假設你對計劃不熟悉,看幾段代碼可能會更有啓發性。
您最初的定義是這樣的:
(define (evens lis)
(cond (;; Check: Recursion stop condition
(null? lis)
'())
(;; Wrong: Calling length at each step => O(n^2)
;; Wrong: Assuming even element if list has even number of elements
(= (modulo (length lis) 2) 0)
;; Wrong: Recursing with the rest of the list, you'll get odds
(cons (car lis) (evens (cdr lis))))
(else
;; Wrong: Recursing with the rest of the list with cdr, you'll get odds
(evens (cdr lis)))))
之後,編輯完你的問題將其更新爲這樣的事情:
(define (evens lis)
(cond (;; Check: Recursion stop condition
(null? lis)
'())
(else
;; Check: Building list with second element
;; Wrong: If lis only has 1 element,
;; (cdr lis) is null and (car (cdr list)) is an error.
(cons (cadr lis)
;; Wrong: Recursing with cdr, you'll get odds
(evens (cdr lis))))))
一個解決辦法是檢查列表有至少第二個元素:
(define (evens lis)
(cond (;; Check: Recursion stop condition 1
(null? lis)
'())
(;; Check: Recursion stop condition 2: list of length = 1
(null? (cdr lis))
'())
(else
;; Check: Building list with second element
;; The previous cond clauses have already sorted out
;; that lis and (cdr lis) are not null.
(cons (cadr lis)
;; Check: Recurse "the rest of the rest" of lis with cddr
(evens (cddr lis)))))
練習:使用if
和or
將此解決方案簡化爲只有2個分支。
單步執行代碼和錯誤應該很明顯。 (這是第一次迭代。) –
您應該添加新代碼,而不是替換舊代碼。現在這個問題是不完整的,其中一部分不再相關。 – itsbruce
[返回每個其他元素的列表的方案過程]的可能重複(http://stackoverflow.com/questions/13318388/a-scheme-procedure-that-returns-a-list-of-every-other-元素) –