Hi!i need to define a function in scheme which takes as argument a list and multiplies all the numbers in that list.
so far i have this:
(define (prod list)(if(null? list) 0(*(car list)(car(cdr list)))))
it gives error..please help
Scheme
Page 1 of 13 Replies  560 Views  Last Post: 16 April 2013  04:38 AM
Replies To: Scheme
#2
Re: Scheme
Posted 16 April 2013  03:28 AM
I wonder if you should separate the expressions with a blank.
Then, do you mean multiplying the values in the list together?
Now you multiply the first two items.
If you are going to make it recursive (as you probably should) don't return zero,
since zero times anything is zero, and that times anything is still zero.
Return 1 instead.
How do you multiply the elements of a list??
You multiply the first element by the PRODUCT of the rest of the list. Right?
Then, do you mean multiplying the values in the list together?
Now you multiply the first two items.
If you are going to make it recursive (as you probably should) don't return zero,
since zero times anything is zero, and that times anything is still zero.
Return 1 instead.
How do you multiply the elements of a list??
You multiply the first element by the PRODUCT of the rest of the list. Right?
#3
Re: Scheme
Posted 16 April 2013  04:21 AM
yu8690, on 16 April 2013  09:32 AM, said:
it gives error..please help
What error does it give? If I run that code and then call the prod function, I don't get any error message and I don't see why you would.
turboscrew, on 16 April 2013  12:28 PM, said:
I wonder if you should separate the expressions with a blank.
He definitely should  for readability. But he doesn't need to for it to be syntactically valid.
#4
Re: Scheme
Posted 16 April 2013  04:38 AM
If you were multiplying, then 0 would seem like a really bad idea.
Let me break out what you have:
Dump result:
So, essentially, (prod '(1 2 3 4 5)) will expand to (* 1 2).
I suspect you want some recursion in there? Perhaps if you did a car and passed the rest to...
You probably want (prod '(1 2 3)) to expand to (* 1 (* 2 (* 3 1))). That is, if the goal was to multiply the numbers together.
Hope this helps.
Let me break out what you have:
(define (prod list) (if (null? list) 0 (* (car list) (car(cdr list))) ) ) (define a '(1 2 3 4 5)) (display "a == ")a (display "(car a) ==" )(car a) (display "(cdr a) ==")(cdr a) (display "(car (cdr a)) == ")(car (cdr a)) (display "(prod a) == ")(prod a)
Dump result:
a == (1 2 3 4 5) (car a) == 1 (cdr a) == (2 3 4 5) (car (cdr a)) == 2 (prod a) == 2
So, essentially, (prod '(1 2 3 4 5)) will expand to (* 1 2).
I suspect you want some recursion in there? Perhaps if you did a car and passed the rest to...
You probably want (prod '(1 2 3)) to expand to (* 1 (* 2 (* 3 1))). That is, if the goal was to multiply the numbers together.
Hope this helps.
This post has been edited by baavgai: 16 April 2013  04:40 AM
Page 1 of 1
