[英]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?我将如何在 Racket 博士中编写一个 function ,它使用一个数字列表(所有数字都是 25)并生成一个新的数字列表,其中每个前面的元素都添加了 50?
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我预期的 output 是
(list 25 75 125 175 225)
To explain the output, the first element stays the same.为了解释 output,第一个元素保持不变。 Then, 50 is added to 25 to give 75. Then, 50 is added to 75 to give 125 and so on.然后,将 50 加到 25 中得到 75。然后,将 50 加到 75 中得到 125,依此类推。
Instead of this output, I get:而不是这个 output,我得到:
(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:我建议在一系列索引上使用map
到 map 并添加:
(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.这将产生一个新列表,其中元素是原始列表中每个x
的每个x + (n * (index of x))
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.