2017-04-25 64 views
0

該函數的用途是使用lisp計算列表中12的出現次數。在列表中計數1 2的Lisp函數

的代碼,我寫道:

(defun count12 (x) 
    (if (null x) 0 
     (if (and (= 1 (car x)) (= 2 (cadr x))) 
      (+ 1 (count12 (cdr x))) 
      (+ 0 (count12 (cdr x))) 
     ) 
    ) 
) 

當我使用它,它會產生錯誤:

錯誤(S),警告(S): *** - = :NIL不是數字

請注意,我正在使用Lisp在線編譯器:rextester

謝謝您的幫助&指南

+1

什麼,如果該列表是1元多長時間?那麼你比較2到零 – jenesaisquoi

+0

是的,我添加了空條件的條件。非常感謝。 –

回答

0

當你到達列表的最後一個元素,你會比較2nil(的nilcadrnil)。

你需要測試單列表:

(defun count12 (x) 
    (if (or (null x) (null (cdr x))) 
     0 
     (if (and (= 1 (car x)) (= 2 (cadr x))) 
      (+ 1 (count12 (cdr x))) 
      (+ 0 (count12 (cdr x)))))) 
+0

非常感謝。 –