3 Replies - 708 Views - Last Post: 16 April 2013 - 04:38 AM

#1 yu8690  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 7
  • Joined: 02-November 10

Scheme

Posted 16 April 2013 - 12:32 AM

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
Is This A Good Question/Topic? 0
  • +

Replies To: Scheme

#2 turboscrew  Icon User is offline

  • D.I.C Addict

Reputation: 100
  • View blog
  • Posts: 644
  • Joined: 03-April 12

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?
Was This Post Helpful? 1
  • +
  • -

#3 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2153
  • View blog
  • Posts: 3,313
  • Joined: 21-June 11

Re: Scheme

Posted 16 April 2013 - 04:21 AM

View Postyu8690, 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.

View Postturboscrew, 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.
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5932
  • View blog
  • Posts: 12,855
  • Joined: 16-October 07

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:
(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

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1