简体   繁体   English

使用Scheme的列表中的数字总和

[英]Sum of numbers in a list using Scheme

I want to sum the numbers in a list without using recursion. 我想在不使用递归的情况下对列表中的数字求和。 I know you can sum a list of numbers like this 我知道你可以总结这样的数字列表

(+ num1 num2 ... numN) (+ num1 num2 ... numN)

but what if you have a list L which equals to '(num1 num2 ... numN) is there a way to make + take the numbers in this list as arguments. 但是如果你有一个等于'(num1 num2 ... numN)的列表L,那么有什么方法可以使这个列表中的数字作为参数。 I need to do this without recursion or helper functions. 我需要在没有递归或辅助函数的情况下执行此操作。

Sure, just use apply : 当然,只需使用apply

(apply + '(1 2 3 4 5 6))   ; same as (+ 1 2 3 4 5 6)
(apply + 1 2 3 '(4 5 6))   ; ditto
(apply + 1 2 3 4 5 '(6))   ; ditto
(apply + 1 2 3 4 5 6 '())  ; ditto

The general answer to the question you seem to be asking -- how to take a list and use it as the arguments -- is apply , as Chris Jester-Young answered. 正如Chris Jester-Young所回答的那样,你似乎要问的问题的一般答案 - 如何列出并使用它作为论据 - 是apply

However, for this particular question, there might some other considerations. 但是,对于这个特定问题,可能还有其他一些考虑因素。 You may want to sum lists of arbitrary size. 您可能想要对任意大小的列表求和。 However, implementations often have some limit of the number of arguments you can call a function with. 但是,实现通常会对可以调用函数的参数数量进行一些限制。 A more reliable solution may be to use some kind of fold function (various implementations have different fold functions) to fold + over the list. 更可靠的解决方案可能是使用某种折叠函数(各种实现具有不同的折叠函数)来折叠+列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM