开发者

Sum of numbers in a list using Scheme

开发者 https://www.devze.com 2023-04-12 10:02 出处:网络
I want to sum the numbers in a list without using recur开发者_如何学Csion. I know you can sum a list of numbers like this

I want to sum the numbers in a list without using recur开发者_如何学Csion. I know you can sum a list of numbers like this

(+ 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. I need to do this without recursion or helper functions.


Sure, just use 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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消