## Product function

You have problems, and we're glad to hear them. Explain the problem, what you have tried, and where you got stuck.
Feel free to share a little info on yourself and the course.
Forum rules
Please respect your teacher's guidelines. Homework is a learning tool. If we just post answers, we aren't actually helping. When you post questions, be sure to show what you have tried or what you don't understand.

### Product function

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:
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)    ))`
dgfrey102790

Posts: 2
Joined: Sat Sep 01, 2018 7:07 pm

### Re: Product function

There are a few ways to do this.

I would guess that you are supposed to use recursion for complex forms.

In other words, have the product function call product on smaller pieces of the input.

nuntius

Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

### Re: Product function

Thanks. I got it with recursion.
Here's what I was able to figure out:
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) (* (product (car x)) (product (cdr x))))        ((numberp x) (* x 1))        (t 1)    ));tests(print (product '((2 2) 3))) --> 12(print (product '(3 5))) --> 15(print (product 'x)) --> 1(print (product '('x 5))) --> 5(print (product '((a 3) (2 1)))) --> 6`
dgfrey102790

Posts: 2
Joined: Sat Sep 01, 2018 7:07 pm

### Who is online

Users browsing this forum: No registered users and 1 guest