1

I looked and looked, but was surprised not to find an answer to this question.

In R5RS scheme, how would you write a procedure that multiplies each element of the list with one-another. If I'm given a list '(4 5 6), the procedure, multiply-list, should return 120. 4*5*6=120.

Thanks in advance.

2
  • You should be able to take an example for addition (such as this one: stackoverflow.com/questions/9151045/scheme-sum-of-list) and trivially adapt it to use multiplication. Commented Sep 26, 2012 at 5:45
  • Thanks Greg! For the record I did try searching for an addition one to base it off of. I've posed a modified version below in case anyone else is looking.
    – Matt
    Commented Sep 26, 2012 at 5:49

3 Answers 3

1

(define (multiply-list l) (apply * l))

As trivial as it gets. That's probably why you never found the answer: no one ever bothered writing it down…

1

The "suggested" way:

(define mult 
  (lambda (the-list)
    (apply * the-list)))

An iterative implementation:

(define mult-it 
  (lambda (the-list)
    (let ((result 1))
      (begin
        (for-each 
         (lambda (x)
           (set! result (* result x)))
         the-list)
        result)))) 

A purely functional and recursive implementation:

(define mult-rec
  (lambda (the-list)
    (if (null? the-list)
        1
        (* (car the-list) (mult-rec (cdr the-list))))))
0
(define (multiply-list list)
  (let loop ((list list) (accum 1))
    (cond
      ((null? list) accum)
      ((not (number? (car list))) '())
      (else (loop (cdr list) (* accum (car list)))))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.