Home > Back-end >  Use map() to multiply a list of numbers by two each using Racket
Use map() to multiply a list of numbers by two each using Racket

Time:05-07

I'm trying to use map() to multiply a list of numbers by two each using Racket in DrRacket. Does anyone know what I'm doing wrong?

(define (make-double List)(map (* List 2))) ; missing lambda
(define (make-double-correct List)(lambda (List) map (* List 2)))
(define (make-double-correct List)(map (lambda (x) (* List 2))))
; Test case: (make-double-correct (list 1 2 3 4 5)) should be (2 4 6 8 10)

CodePudding user response:

map takes in 2 arguments, a lambda, and the list itself. The argument of the lambda refers to each element that is mapped, so we multiply that by 2:

(define (make-double-correct lst)
  (map (lambda (e) (* 2 e)) lst))

CodePudding user response:

map takes two arguments : a procedure and a list (map procedure list)

So you can use either a lambda or a procedure to double list elements

here I defined a double procedure:

(define (double x)
  (* x 2))

(define (make-double-correct lst)
  (map double lst))

this is the same with above procedure only includes a lambda instead of double procedure:

(define (make-double lst)
  (map (lambda (x)(* x 2)) lst))

You can also write a scale procedure and double, triple, quadruple, etc. a list :

(define (scale-list items factor)
  (map (lambda (x) (* x factor))
       items))
  • Related