Page 1 of 1

Product function

PostPosted: Sat Sep 01, 2018 7:12 pm
by dgfrey102790
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)
    )
)

Re: Product function

PostPosted: Sun Sep 02, 2018 12:47 pm
by nuntius
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.

Re: Product function

PostPosted: Tue Sep 04, 2018 11:45 am
by dgfrey102790
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