几周来我一直在尝试实现 Accumulate 函数。我已经正确实现了一个“Map”函数,它遍历列表并在每个元素上运行一个函数。
我正在使用这个函数来实现“累积”
(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
;
您想要实现适用于列表的折叠过程,您不需要使用map
,简单地依次处理每个元素。这是更喜欢它:
(define accumulate
(lambda (op base func ls)
(if (null? ls)
base
(op (func (car ls))
(accumulate op base func (cdr ls))))))
例如:
(accumulate + 0 sqr '(1 2 3))
=> 14
(accumulate * 1 sqr '(1 2 3))
=> 36
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)