【发布时间】:2016-09-24 00:08:14
【问题描述】:
现在,我一直在尝试实现 Accumulate 函数几个星期。我已经正确实现了一个“映射”函数,它遍历一个列表并在每个元素上运行一个函数。
我正在使用这个函数来实现“累积”
(define accumulate
(lambda (op base func ls)
(if(null? ls)
ls
(cond (not (null? (cdr ls)) (op base (map func ls) (accumulate op base func (cdr ls))))
(op base (map func ls) (op base (func(car ls))))
)
)))
;It gets to a point (the last element) after applying the map function to each element,
;where it is '(number) instead of an expected "number" (outside of () ). I cannot figure out
;how to circumvent this.
我一直不知道如何做到这一点。这样做的正确方法是什么?
预期的结果是:
; accumulate: combines using OP the values of a list LS after mapping a function FUNC on it
; (accumulate + 0 sqr '(1 2 3)) => 14
; (accumulate * 1 sqr '(1 2 3)) => 36
;
【问题讨论】:
-
我认为您的
cond声明不正确。(cond ((not (null? (cdr ls))) (op base ... -
accumulate的输出到底应该是什么?请提供具有预期输出的示例输入 -
另外,你为什么需要
map?您确定您的输入是 lists 的列表吗?
标签: list scheme map-function accumulate