I'm just starting out on lisp. I'm trying to make a product function written in Lisp. The function should take in an arbitrary parameter x, and returns the product of all numerical values contained in x. It should produce the following:
>(product 'x) -> 1
>(product '(x 5)) -> 5
>(product '((2 2)3)) -> 12
>(product '((a 3)(2 1))) -> 6
I was able to do the following:
(defun product (x)
"This function takes in an arbitrary parameter x, and returns the product of all numeric values contained within x."
(cond
((consp x) (* (car x)(product (cadr x))))
((numberp x) x)
(t 1)
)
)
This handles the cases like
(product '(2 5))-> 10
(product 'x) -> 1
But not for ones like:
>(product '(x 5)) -> 5
>(product '((2 2)3)) -> 12
I'm not sure where to go from here.
The first clause of your cond
expression reads as follows:
If x is a cons cell, multiply its first element (assumed to be a number) with the result of calling
product
on its second element (or NIL).
Both (product '(x 5))
and (product '((2 2) 3))
fail because the first element is not a number. You should multiply by (product (car x))
instead of (car x)
, in order to convert your arbitrary terms into numbers.
Note also that recursing on cadr
is not enough to iterate over all elements of your input list. You probably intended to use cdr
.