Python的Reduce函数——用Scheme编写
晚上!
我需要在Scheme中编写一个reduce函数,它的工作方式就像Python中内置的reduce函数一样。在Scheme中编写reduce函数很容易:
(define (reduce fn lis identity)
(if (null? lis)
identity
(fn (car lis)
(reduce fn (cdr lis) identity))))
但是,此代码与Python的reduce不同,后者只需要两个参数(函数和要reduce的项目列表)。
任何人都可以帮助我编写一个以这种方式工作的Scheme函数吗?
(>(reduce * '(2 4 5 5)) => 200,是我们教授的例子。)
非常感谢,伙计们。您真是太有帮助了<3
ETA:非常感谢 Levien 先生和 Jester-Young 先生。您提供了足够多的信息来帮助我自己解决问题。 *拥抱
Evening!
I need to write a reduce function in Scheme that works just as the built-in reduce function in Python. It's easy to write a reduce function in Scheme:
(define (reduce fn lis identity)
(if (null? lis)
identity
(fn (car lis)
(reduce fn (cdr lis) identity))))
However, this code isn't identical to the Python reduce, which takes only two arguments (the function and a list of items to reduce).
Can anyone help me write a Scheme function that works this way?
(>(reduce * '(2 4 5 5)) => 200, is our professor's example.)
Thanks so much, guys and gals. You are so helpful <3
ETA: To Mr. Levien and Mr. Jester-Young, thank you so very much. You provided the perfect amount of information to help me figure the problem out on my own. *hug
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那很容易。累加器使用列表的第一个元素进行初始化:
随意使用除 srfi-1 中的 Fold 之外的另一个归约函数(例如,reduce、fold-right ...)或使用您自己的函数。您的列表至少需要一个元素。
That is easy. The accumulator is initialized with the first element of the list:
Feel free to use another reduce function than fold from srfi-1 (like reduce, fold-right ...) or use your own. Your list needs one element at least.
拥有身份允许您的函数处理大小为零或更大的列表 - 当它是空列表时,您将获得身份。如果没有标识,该函数将仅适用于一个或多个元素的列表。有些函数自然具有恒等式(零表示加法,一表示乘法等)。其他人则不然,尤其是
min
和max
,尤其是大整数。你应该能够弄清楚剩下的:)
Having an identity allows your function to work with a list of size zero or more - when it's an empty list, you get the identity. Without an identity, the function will only work with a list of one or more elements. Some functions naturally have an identity (zero for addition, one for multiplication, etc). Others don't -
min
andmax
in particular, especially over big ints.You should be able to figure out the rest :)
下面是尾递归版本。你的教授不太可能喜欢它(因为它没有演示递归;-)),但至少它会给你一些如何去做的想法。
正如 Raph Levien 的出色回答所暗示的那样,如果传入列表为空(这就是
identity
参数的用途),则此版本将无法工作。在这种情况下,您将收到错误(因为您不能car
或cdr
为空列表)。Below is a tail-recursive version. Your professor isn't likely to like it (since it doesn't demonstrate recursion ;-)), but at least it will give you some idea how to go about it.
As hinted in Raph Levien's excellent answer, this version will not work if the incoming list is empty (that'd be what the
identity
parameter is for). You will, in this case, get an error (since you can'tcar
orcdr
an empty list).