jbreard Posted May 27, 2021 Share Posted May 27, 2021 Hello everyone, Do anyone know how to calculate efficiently the cumulative sum list of a list of value without using a loop explicitly ? Given a list of value (a b c d e...), I want to calculate the list (a (a+b) (a+b+c) (a+b+c+d)....). I'm sure there is a simple way to do such a thing with recursion but I can't quite understand yet how these particuliar functions work. I searched the forum and I found approaching topics but nothing that I could understand enough to perform such a function. Thanks a lot and have a great day, Jacques Quote Link to comment Share on other sites More sharing options...
Stefan BMR Posted May 27, 2021 Share Posted May 27, 2021 (defun _sums (l / s) (setq s 0) (mapcar '(lambda (x) (setq s (+ s x))) l) ) _$ (_sums '(1 2 3 4)) (1 3 6 10) _$ 1 Quote Link to comment Share on other sites More sharing options...
jbreard Posted May 27, 2021 Author Share Posted May 27, 2021 It works like a charm ! Thanks so much Stefan Now I will have to understand how it works so well. Thanks again, Jacques Quote Link to comment Share on other sites More sharing options...
Lee Mac Posted May 27, 2021 Share Posted May 27, 2021 Another, for fun, recursive & inefficient - (defun trinum ( l ) (if (cdr l) (cons (car l) (trinum (cons (+ (car l) (cadr l)) (cddr l)))) l ) ) Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.