的問題是問到數E有多少次出現在整數列表:(數E L)如何搜索的時代元素使用遞歸
這裏是什麼我迄今..(我明明知道它的不正確的)
(define count(lambda(e L)
(cond
((null? L) 0)
((= e (car L)) (e(cdr L)))
(#t (count(e(cadr L))))
)))
任何想法?
的問題是問到數E有多少次出現在整數列表:(數E L)如何搜索的時代元素使用遞歸
這裏是什麼我迄今..(我明明知道它的不正確的)
(define count(lambda(e L)
(cond
((null? L) 0)
((= e (car L)) (e(cdr L)))
(#t (count(e(cadr L))))
)))
任何想法?
有在你的代碼的幾個錯誤,這裏有一個修正版本:
(define count
(lambda (e L)
(cond
((null? L) 0)
((= e (car L)) (+ 1 (count e (cdr L))))
(else (count e (cdr L))))))
請注意:
cdr
,不cadr
count
在第二種情況下else
,不#t
你缺少的關鍵步驟是,當你做找到值:你需要回到
plus(1 count(e(cdr L)))
的named let
遞歸可能有助於澄清過程:
(define (counte L e)
(let loop ((L L) ; start with full list
(c 0)) ; and 0 as count
(cond
[(empty? L) c] ; if end reached, return count
[(equal? e (car L)) ; if first item equals e
(loop (cdr L) ; loop with rest of list and incremented count
(add1 c))]
[else
(loop (cdr L) ; else loop with rest of list without incrementing count
c)]
)))
我我對這一行進行了修正,(#t(count(cdr L)))我仍然無法弄清楚上面的行會發生什麼 – Icescout