I am trying to write a weird function, so bear with me here. This function should take a list L
as a parameter and have a sum
variable. If L
is not a list, it should return nil
. Otherwise, it should iterate through each element of the list and do the following:
Here's the code I have, but it returns 0 regardless of arguments passed in:
(defun sigsum (L)
(let ((sum 0)) ;;variable sum
(if (not (listp L)) ;;if L is not a list
nil ;;return nil
(dotimes (i (length L)) ;;otherwise loop through L
(if (numberp (elt L i)) ;;if each element is a number
(if (< (elt L i) 0) ;;if is less than 0 subtract 1 from sum
(- sum 1)
(if (> (elt L i) 0) ;;if greater than 0 add 1 to sum
(+ sum 1))
(+ sum 0)) ;;else add 0 to sum
(+ sum 0))) ;;not a number so add 0 to sum
)
sum) ;;return sum
)
As always, any help is greatly appreciated.
(defun discrete (lis)
(cond
((and (listp lis) (not (equal lis nil)))
(let ((sum 0))
(loop for item in lis do
(cond ((or (not (numberp item)) (equal 0 item)) t)
((and (numberp item) (> item 1)) (setf sum (+ 1 sum)))
((and (numberp item) (< item 1)) (setf sum (- sum 1)))))
sum))))
Usage:(discrete '(-1 2 3 0 2 2 -1 2 34 0 -1))
=> 3
(discrete '(-4 a b))
=> -1
(discrete '())
=> NIL
(discrete '(a s d f))
=> 0