Jonathan Handojo Posted November 30, 2019 Share Posted November 30, 2019 Hello fellow hackers, This post probably doesn't reflect the title as what you think it is, but I think it will still do. What I want to achieve is from a list of integers or reals as example below: (1 2 3 4 5 6 7) into: (1 3 6 10 15 21 28) where the value on the nth index is the sum of all the integers from the first index to that index. Anyone know a good way to achieve this? I'm hoping to use a simple mapcar function but nothing's coming to my head. (P.S. I've run an error handle so that only integers and reals are allowed in the list.) Thanks, Jonathan Handojo Quote Link to comment Share on other sites More sharing options...
Lee Mac Posted November 30, 2019 Share Posted November 30, 2019 (edited) (defun foo ( l ) (defun bar ( l ) (if l (cons (apply '+ l) (bar (cdr l)))) ) (reverse (bar (reverse l))) ) _$ (foo '(1 2 3 4 5 6 7)) (1 3 6 10 15 21 28) Edited November 30, 2019 by Lee Mac 1 Quote Link to comment Share on other sites More sharing options...
Lee Mac Posted November 30, 2019 Share Posted November 30, 2019 (edited) (defun foo ( l / x ) (setq x 0) (mapcar '(lambda ( y ) (setq x (+ x y))) l) ) _$ (foo '(1 2 3 4 5 6 7)) (1 3 6 10 15 21 28) Edited November 30, 2019 by Lee Mac Quote Link to comment Share on other sites More sharing options...
Jonathan Handojo Posted November 30, 2019 Author Share Posted November 30, 2019 2 minutes ago, Lee Mac said: (defun foo ( l / x ) (setq x 0) (mapcar '(lambda ( y ) (setq x (+ x y))) l) ) _$ (foo '(1 2 3 4 5 6 7)) (1 3 6 10 15 21 28) That was quick! What a nice method, I thought I would've used apply on some case, but that's a nice trick. Thanks Lee! Quote Link to comment Share on other sites More sharing options...
Grrr Posted November 30, 2019 Share Posted November 30, 2019 Not elegant as Lee's : ; (foo '(1 2 3 4 5 6 7)) (defun foo ( L ) ('( (f) (cdr (f 0 L))) '( (c L) (if L (cons c (f (+ c (car L)) (cdr L))) (list c) ) ) ) ) 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.