Product function
Posted: Sat Sep 01, 2018 7:12 pm
I'm very new to Lisp.
I'm trying to make a product function that takes in an arbitrary parameter x. The function should return the product of all numeric values contained within x. For example,
> (product ’x) 1
> (product ’(x 5)) 5
> (product ’((2 2) 3) ) 12
> (product ’((a 3) (2 1)) ) 6
I've been given the hint to use consp and numberp. I was able to figure out if the parameter is just 'x --> 1, or if it's like '(2 5) --> 10. What I can't figure out is how to deal with a letter and a number, or dealing with sublists.
Here's what I've done so far:
I'm trying to make a product function that takes in an arbitrary parameter x. The function should return the product of all numeric values contained within x. For example,
> (product ’x) 1
> (product ’(x 5)) 5
> (product ’((2 2) 3) ) 12
> (product ’((a 3) (2 1)) ) 6
I've been given the hint to use consp and numberp. I was able to figure out if the parameter is just 'x --> 1, or if it's like '(2 5) --> 10. What I can't figure out is how to deal with a letter and a number, or dealing with sublists.
Here's what I've done so far:
Code: Select all
(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)(cadr x)))
((numberp x) x)
(t 1)
)
)