Question

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.

Was it helpful?

Solution 3

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

OTHER TIPS

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

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))))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top