New to lisp, compiler telling me this is a bad lambda -
i new lisp , have little experience lambda expressions @ point in college career. homework exercise problem states:
- write lisp function countallnumbers counts number of numeric atoms in list, no matter how nested are. example: (countallnumbers ‘(1 2 (3 b 4 (5 6)))) returns value 6
i using lispworks compile code , have been getting error:
badly formed lambda: (numberp (car list) (+ 1 (countallnumbers (cdr list))))
here code:
(defun countallnumbers(list) (if (eql list nil) nil (let ((elem (car list)) (restlist (cdr list))) (if (listp elem) (append (countallnumbers elem) (countallnumbers restlist)) (append (cons elem nil) (countallnumbers restlist))) ((numberp (car list) (+ 1 (countallnumbers (cdr list)))))))) (write (countallnumbers '(1 2 3 b (4 c))))
so far have tested , got work line starts calling numberp. figured easiest deal if input converted list of atoms, no nesting. making making sense of appreciated
the syntax error in:
((numberp (car list) (+ 1 (countallnumbers(cdr list)))))
since, given program, list read form, first element should either symbol function or lambda list (i.e. (lambda (args) body)
) , rest arguments of function. if, on other hand, have written condition evaluated (given predicate numberp
), written outside if
form has condition (differently cond
).
your function has main problem: should return number, returning lists both when input empty list (the result should 0
, not nil
), through append
in other cases.
there other minor stylistic issues:
- the usual way of testing empty list
(endp list)
, , not(eql list nil)
- the closed parentheses should not written on line themselves.
here possible definition of function:
(defun countallnumbers(list) (cond ((endp list) 0) ((numberp (car list)) (1+ (countallnumbers (cdr list)))) ((listp (car list)) (+ (countallnumbers (car list)) (countallnumbers (cdr list)))) (t (countallnumbers (cdr list)))))
note cond
used instead of if
since 4 cases must checked: when list empty, when car number, or list, or neither number nor list. in cases integer returned, both termination case, when list null, , recursive cases. 1+
function add 1 argument, while note in case in car
list, result obtained adding count of numbers of car count of numbers of cdr of list.
Comments
Post a Comment