实施“收集"操作.计划中的功能 [英] Implementing "Accumulate" Function in Scheme

查看:32
本文介绍了实施“收集"操作.计划中的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想尝试实现一个累积功能,现在已经有几个星期了.我已经正确实现了地图"功能,该功能可遍历列表并在每个元素上运行一个功能.

I've been hung on trying to implement an Accumulate function for a couple weeks, now. I have properly implemented a "Map" function, that iterates across a list and runs a function on each element.

我正在使用此功能来实现累计"

I am using this function to implement "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.

我坚持如何正确解决这个问题.正确的方法是什么?

I'm stuck on how to get this right. What is the right way to do 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,只需依次处理每个元素即可.像这样:

You want to implement a folding procedure that works for a list, you don't need to use map, simply process each element in turn. This is more like it:

(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

这篇关于实施“收集"操作.计划中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆