简体   繁体   中英

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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