Reputation: 231
Hi everyone I am trying to construct a mixed list with letters and numbers. For example when you call the funciton (inc-list1 '(cat 4 dog 3 x 5)) => (cat 5 dog 4 x 6). I am pretty sure the logic is right, so i think i am missing something from the syntax. Here is my code
(defun inc-list1 (list)
(cond ((null list)
nil
)
(numberp (first list)
(cons ( + 1 (first list)) (inc-list1 (rest list)))
)
(T
cons (first list) (inc-list1 (rest list))
)
)
)
Upvotes: 2
Views: 91
Reputation:
An example of how you could have approached the problem:
(defun mapcar-if (list test if-true &optional (otherwise #'identity))
(mapcar
#'(lambda (x)
(funcall
(if (funcall test x)
if-true
otherwise) x)) list))
(mapcar-if '(cat 4 dog 3 x 5) #'numberp #'1+)
Which would make the function a little bit more useful in other situations too.
Your code:
(T cons ...)
doesn't do what you think it does. You probably wanted to call cons
rather then simply mention it. Mentioning it in the way you did has no effect and no side effect (it would have side effect, if the symbol cons was unbound - i.e. you'd receive an error). Whatever happens next is the result of the previous error. Calling (first list)
has no side effect too (in your case).
"Consing" the list in the way you did isn't a particularly good technique. Because this technique is already implemented in other functions (like mapcar
, reduce
etc.) They were written with the purpose in mind to reduce the amount of text you have to type to write a program, and to make it easier to read, once you have written it. ;)
Upvotes: 1
Reputation: 20248
There are various typos in your code. Here is a fixed version
(defun inc-list1 (list)
(cond ((null list)
nil
)
((numberp (first list))
(cons ( + 1 (first list)) (inc-list1 (rest list)))
)
(t
(cons (first list) (inc-list1 (rest list)))
)
)
)
Note the added parens around the numberp
and cons
function calls and the t
in lower case.
Upvotes: 0