schemelispracketmultiplicationcdr

multiplying list of items by a certain number 'x'


How would you write a procedure that multiplies each element of the list with a given number (x).If I give a list '(1 2 3) and x=3, the procedure should return (3 6 9)

My try:

(define (mul-list list x)
(if (null? list)
1
(list(* x (car list))(mul-list (cdr list)))))

The above code doesnt seem to work.What changes do I have to make ? Please help

Thanks in advance.


Solution

  • This is the text book example where you should use map, instead of reinventing the wheel:

    (define (mul-list lst x)
      (map (lambda (n) (* x n)) lst))
    

    But I guess that you want to implement it from scratch. Your code has the following problems:

    This should fix all the bugs:

    (define (mul-list lst x)
      (if (null? lst)
          '()
          (cons (* x (car lst))
                (mul-list (cdr lst) x))))
    

    Either way, it works as expected:

    (mul-list '(1 2 3) 3)
    => '(3 6 9)