我的计划是盲目的,我觉得一旦我回答了这个问题,我剩下的家庭作业应该会顺利进行。
我正在定义一个函数,它以列表作为其唯一的参数,然后返回相同的列表,并将第一个元素添加到其余元素中。例如:
(addFirst ‘(4 3 2 1)) => (8 7 6 5)我有一种感觉,我应该在这里使用地图和汽车功能…但我似乎就是不能完全正确。我当前版本的代码如下所示:
(define (addlist x) ;adds the first element of a list to all other elements
(define a (car x)) ;a is definitely the first part of the list
(map (+ a) x)
)怎样才能让加法函数以这种方式工作呢?显然,我不能提供列表作为参数,但我应该再次使用car还是递归?
好的,对于后人来说,这是完整的,正确的,格式化的代码:
(define (addlist x) ;adds the first element of a list to all other elements
(define a (car x)) ;a is definitely the first part of the list
(map (lambda (y) (+ a y)) x)
)发布于 2012-03-22 01:39:26
Map接受一个函数和n个列表。因此,您需要将(+ a)转换为只接受一个参数的函数(因为您希望映射到一个列表上)。
(map (lambda (item) ... do something to add a to item ...) x)https://stackoverflow.com/questions/9809836
复制相似问题