2017-03-06 17 views
1
出現在列表中計劃量

的問題是問到數E有多少次出現在整數列表:(數E L)如何搜索的時代元素使用遞歸

這裏是什麼我迄今..(我明明知道它的不正確的)

(define count(lambda(e L) 
      (cond 
      ((null? L)   0) 
      ((= e (car L)) (e(cdr L))) 
      (#t (count(e(cadr L)))) 
))) 

任何想法?

+0

我我對這一行進行了修正,(#t(count(cdr L)))我仍然無法弄清楚上面的行會發生什麼 – Icescout

回答

1

有在你的代碼的幾個錯誤,這裏有一個修正版本:

(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
0

你缺少的關鍵步驟是,當你找到值:你需要回到

plus(1 count(e(cdr L))) 
0

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)] 
    )))