我正试着用Lisp写代码,递归地计算以number开头的子列表。我一直在尝试使用numberp,但是当我的代码到达一个原子时,它不会计算列表的其余部分。
这里有我的代码,
(defun nombres (liste)
(cond
((atom liste) 0)((atom (car liste)) 0)
((and (numberp (caar liste)) (+ (nombres (cdr liste)) 1)))
(t (nombres (cdr liste))) ) )我可以得到子列表的计数,但当到达一个原子时,它不会计算其余的。
[67]> (nombres '((a b d) (5 g) (7 m)))
2
[68]> (nombres '((a b d) (5 g) g (7 m)))
1当我用(listp (汽车列表))测试子列表时,它给我的结果为空。
[69]> (defun nombres (liste)
(cond
((atom liste) 0)((atom (car liste)) 0)
((listp (car liste))(and (numberp (caar liste)) (+ (nombres (cdr liste)) 1))) (t (nombres (cdr liste))) ) )
NOMBRES
[70]> (nombres '((a b d) (5 g) g (7 m) m))
NIL我想要这样的东西:
(nombres '((a b d) a (5 g) (b) (7 m) j (8 h l g)))
3谢谢你的帮忙
发布于 2016-07-27 14:09:48
你需要考虑你需要处理的案件。
在列表末尾=>
这些将非常容易地转换为COND
(cond ((endp list) ...) ; 1
((and (listp (car list)) ; 2
(numberp (caar list)))
...)
(t ...) ; 3使用累加器作为可选参数,很容易填写计数:
(defun count-sublists (list &optional (acc 0))
(cond ((endp list) acc)
((and (listp (car list))
(numberp (caar list)))
(count-sublists (cdr list) (1+ acc)))
(t (count-sublists (cdr list) acc))))
(count-sublists '((a b d) a (5 g) (b) (7 m) j (8 h l g)))
;=> 3发布于 2016-07-27 17:27:44
标准的Common Lisp函数count-if更易于使用:
CL-USER > (count-if (lambda (item)
(and (consp item)
(numberp (first item))))
'((a b d) a (5 g) (b) (7 m) j (8 h l g)))
3https://stackoverflow.com/questions/38604335
复制相似问题