简体   繁体   中英

How would I write a function in Dr. Racket which consumes a list of numbers and produces a new list of numbers which have been mapped?

How would I write a function in Dr. Racket which consumes a list of numbers (all numbers are 25) and produces a new list of numbers with 50 added to each preceding element?

Here is my code so far:

(define (new-funct f lst)
  (cond
    [(empty? lst) empty]
    [else (cons (f (first lst))
            (new-funct f (rest lst)))]))

(define (make-addition m)
  (lambda (n) (+ m n)))

(define add50 (make-addition 50))

If I type in:

(new-funct add50 (list 25 25 25 25 25)) 

My expected output is

(list 25 75 125 175 225)

To explain the output, the first element stays the same. Then, 50 is added to 25 to give 75. Then, 50 is added to 75 to give 125 and so on.

Instead of this output, I get:

(list 75 75 75 75 75)

How would I correct my code? Thanks.

I recommend using map to map over a range of the indices and add:

(define (agg-adder n lst)
  (map
    (λ (i x) (+ x (* n i)))
    (range (length lst))
    lst))

This will result in a new list where the elements are each x + (n * (index of x)) for each x in the original list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM