我正在研究一個查找串列中第一個奇數的遞回函式。它按預期作業。
但是當串列中沒有奇數時,它會回傳錯誤。我想用某種“沒有找到奇數值”的訊息來控制這個錯誤。
單次測驗遞回函式
defun find-first-odd (x)
(cond ((oddp (first x)) (first x))
(t (find-first-odd (rest x)))))
(find-first-odd '(2 2 10 3 4 6 4)) ; => 3
(find-first-odd '(2 2 10 4 6 4)) ;=> value nil is not an integer
(find-first-odd '(2 2 10 4 6 4 . 2)) ;=> 2 is not type list
uj5u.com熱心網友回復:
您需要測驗串列是否為空并執行適當的操作。一般來說,任何遞回搜索串列的函式都需要終止測驗,因此看起來像:
(defun search-list-for (l ...)
(cond ((null l)
...)
(<(first l) is what we're after>
...)
(t
(search-list-for (rest l) ...))))
在這種情況下:
(defun find-first-odd (l)
(cond
((null l)
nil) ;or whatever
((oddp (first l))
(first l))
(t
(find-first-odd (rest l)))))
您很幸運,對于您的特定功能,雖然(first '())在 CL 中是完全合法的,但它不是數字,因此您會收到錯誤。通常,您將無法終止:
(defun contains-thing-p/broken (l thing)
(cond
((eql (first l) thing)
t)
(t
(contains-thing-p/broken (rest l) thing))))
如果不在串列中,則不會終止thing,并且必須使用上述框架撰寫:
(defun contains-thing-p (l thing)
(cond
((null l)
nil)
((eql (first l) thing)
t)
(t
(contains-thing-p (rest l) thing))))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528331.html
標籤:递归通用语言
上一篇:如何在回圈中命令Ajax呼叫
