Page 1 of 1

Basic Function Help

Posted: Sun Oct 17, 2010 7:13 pm
by B-rock
Hello fellow board members,

I have sort of hit a dead end with ideas for a simple function I am trying to write called sumprod. Basically, it finds the sum of the product of two separate lists. So for example: (sumprod '(1 2 3) '(2 3)) --> 12, since (1*2*3) + (2*3) = 12.

I know how to find the product of one list, but I am not sure how I would go about finding the product of the second let alone adding its total to the product of the first list.

Here is the necessary Common Lisp code to find the product of one list.

Code: Select all

(defun sumprod (D E)
        (cond
                ((null D) 1)
                (t (* (car D) (sumprod (cdr D) E)))
        )
)
Here is a slightly modified version that also finds the product of the second list but multiplies it with the product of the first list instead of adding it. I know exactly why its doing that, but it's the closest I have coming to solving this one.

Code: Select all

(defun sumprod (D E)
	(cond
		((null E) 0)
		((null D) (*(car E) (sumprod D (cdr E))))
		((* (car D)(sumprod (cdr D) E)))
	)
)
If anything is unclear or needs more explanation, let me know. Thanks for any insight or advice you might be able to supply.

Brock

Re: Basic Function Help

Posted: Sun Oct 17, 2010 8:32 pm
by nuntius
Does it have to be a single function? Helper functions are often nice.
B-rock wrote:Here is the necessary Common Lisp code to find the product of one list.

Code: Select all

(defun sumprod (D E)
        (cond
                ((null D) 1)
                (t (* (car D) (sumprod (cdr D) E)))
        )
)
Let's fix the indentation, name this function to match what it currently does, and replace the if/else cond with an if.

Code: Select all

(defun list-prod (list)
  (if (null list)
    1
    (* (car list) (list-prod (cdr list)))))
(Note: the (null list) could be replaced by a bare list if you switch the order of the clauses.)

Now that you have a function to find the list-prod for one list, can you write another function that uses it to find the sum for multiple lists?

If you do need this to be a single function that recurses on both lists at once, you could either use &optional parameters to pass accumulator variables down the recursion, or multiple valuesto pass them back up. If it has to be a single function, but you can recurse each list individually, then labels is your friend.

Re: Basic Function Help

Posted: Mon Oct 18, 2010 8:58 am
by B-rock
Hello nuntius,

Thank you so much for the help! I have no idea why it didn't occur to me that I could use a helper function. I have it all figured out now. Thanks again.

B-rock

Re: Basic Function Help

Posted: Tue Oct 19, 2010 7:22 pm
by findinglisp
See also REDUCE.