我有一个非线性列表。我需要找出初始列表中任何级别的子列表的数量,其中奇数级别的数值原子的总和是偶数。肤浅的水平计为1.我写了类似的东西:
(defun numbering (l level)
;counts the levels that verify the initial conditions
(cond
((null l) l)
((and (verify (sumlist l)) (not (verify level))) (+ 1 (apply '+ (mapcar#' (lambda (a) (numbering a (+ 1 level))) l))))
(T (apply '+ (mapcar#' (lambda (a) (numbering a (+ 1 level))) l )))
)
)
(defun verify (n)
;returns true if the parameter "n" is even, or NIL, otherwise
(cond
((numberp n)(= (mod n 2) 0))
(T f)
)
)
(defun sumlist (l)
;returns the sum of the numerical atoms from a list, at its superficial level
(cond
((null l) 0)
((numberp (car l)) (+ (car l) (sumlist(cdr l))))
(T (sumlist(cdr l)))
)
)
(defun mainNumbering (l)
; main function, for initializing the level with 1
(numbering l 1)
)
如果我运行“(mainnum'(1 2(ab 4)8(6 g)))”我收到错误:“未定义的函数MAPCAR#用参数调用((LAMBDA(A)(NUMEROTARE A#)) (1 2(AB 4)8(6 G)))。“
有谁知道,我错过了什么?提前谢谢!
答案 0 :(得分:1)
嗯,这是真的,没有mapcar#
这样的功能,它只是一个错字,你在这一行中遗漏了空间:
(T (apply '+ (mapcar#' (lambda (a) (numbering a (+ 1 level))) l )))
应该是:
(T (apply '+ (mapcar #'(lambda (a) (numbering a (+ 1 level))) l )))
答案 1 :(得分:0)
如果我已正确解释您的规范,这是一个可能的解决方案:
(defun sum(l)
(loop for x in l when (numberp x) sum x))
(defun test(l &optional (level 1))
(+ (if (and (oddp level) (evenp (sum l))) 1 0)
(loop for x in l when (listp x) sum (test x (1+ level)))))
(test '(1 2 (a b 4) 7 (6 2 g) (7 1 (2 (3) (4 4) 2) 1 a))) ; => 2
应用于列表的函数sum
返回其所有数字的总和(不输入其子列表)。
函数test
,对于具有奇数级别的列表,对其数字求和,如果结果为偶数,则将1加到应用于l,0子列表的函数结果的总和上否则。
答案 2 :(得分:0)
在编号时,你应该添加l是一个数字的情况,所以 (defun编号(l级) ;计算验证初始条件的级别
(cond
((null l) l)
((atom l)0)
((and (verify (sumlist l)) (not (verify level))) (+ 1 (apply '+ (mapcar #' (lambda (a) (numbering a (+ 1 level))) l))))
(T (apply '+ (mapcar #'(lambda (a) (numbering a (+ 1 level))) l )))
)
)
将解决问题