1

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.

mike
  • 49
  • 1
  • 8

2 Answers2

2

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:

  • You should not call list a parameter, that clashes with the built-in procedure of the same name - one that you're currently trying to use!
  • The base case should return an empty list, given that we're building a list as output
  • We build lists by consing elements, not by calling list
  • You forgot to pass the second parameter to the recursive call of mul-list

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)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Thanks a lot! Can you please suggest me a beginners book for learning Scheme :) – mike Oct 03 '16 at 01:03
  • @mike sure, with pleasure :) . "The Little Schemer" and "How to Design Programs" are fantastic, and "Structure and Interpretation of Computer Programs" is one of the best programming books ever written, although it's a tad more advanced – Óscar López Oct 03 '16 at 01:05
  • Thank you so much :) Óscar López . That was a nice list – mike Oct 03 '16 at 03:10
  • @ÓscarLópez I *was* going to expand your answer by talking about tail recursion and offer an alternative way to write the `map` procedure... But the more I learn about racket's stack, the less this seems important. Do you think it would be beneficial for me to introduce this topic and demonstrate some workarounds? I ask you specifically because I don't want to waste the time of other experts (like you) by potentially muddying the water with things I may not understand as well as you. – Mulan Oct 03 '16 at 07:52
  • @naomik It'd be ok to show a tail recursive version, but bear in mind that OP is still learning and it might be an advanced topic for him ;) Besides, `map` is usually implemented in a non-tail-recursive fashion. – Óscar López Oct 03 '16 at 15:23
0

For and its extensions (for*, for/list, for/first, for/last, for/sum, for/product, for/and, for/or etc: https://docs.racket-lang.org/reference/for.html) are very useful for loops in Racket:

(define (ml2 lst x)
  (for/list ((item lst))
    (* item x)))

Testing:

(ml2 '(1 2 3) 3)

Output:

'(3 6 9)

I find that in many cases, 'for' implementation provides short, simple and easily understandable code.

rnso
  • 23,686
  • 25
  • 112
  • 234