Common lisp 递归地计算以数字开头的子列表
我试图用Lisp编写代码,递归地计算以数字开头的子列表。我一直在尝试使用Common lisp 递归地计算以数字开头的子列表,common-lisp,Common Lisp,我试图用Lisp编写代码,递归地计算以数字开头的子列表。我一直在尝试使用numberp,但是当我的代码到达一个atom时,它并不计算列表中的其余部分 这里有我的代码 (defun nombres (liste) (cond ((atom liste) 0)((atom (car liste)) 0) ((and (numberp (caar liste)) (+ (nombres (cdr liste)) 1))) (t (nombres (cdr liste)))
numberp
,但是当我的代码到达一个atom时,它并不计算列表中的其余部分
这里有我的代码
(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(carlist)测试子列表时,它给我零
[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
感谢您的帮助您需要考虑需要处理的案例
条件
:
(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
标准通用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)))
3
欢迎阅读StActExcel。请阅读您的问题,为其清晰化。<代码>(计数)(lambda(list)(和(CONSP列表)(编号(第一列表)))”((a b d)a(5 g)(b)(7 m)j(8 H L g))< /代码>谢谢您的响应。