Discussion:
walk through list and add all n'th item
(too old to reply)
B. Pym
2024-07-19 03:17:36 UTC
Permalink
Wow: loop macro rulez, somehow..
(loop for (a b c d) on (list 1 2 3 4 5 6 7 8) by #'cddddr
sum a into a-sum
sum b into b-sum
sum c into c-sum
sum d into d-sum
finally (return (list a-sum b-sum c-sum d-sum)))
Yeah, i might consider this code as beautiful
olivier
Gauche Scheme

(use gauche.lazy)
(use util.match)

(define data (lrange 1 57))

(match (lslices data 4)
[((a b c d) ...)
(map (cut fold + 0 <>)
(list a b c d))])

(378 392 406 420)
Kaz Kylheku
2024-07-19 17:22:43 UTC
Permalink
Post by B. Pym
Wow: loop macro rulez, somehow..
(loop for (a b c d) on (list 1 2 3 4 5 6 7 8) by #'cddddr
sum a into a-sum
sum b into b-sum
sum c into c-sum
sum d into d-sum
finally (return (list a-sum b-sum c-sum d-sum)))
Yeah, i might consider this code as beautiful
olivier
Gauche Scheme
(use gauche.lazy)
(use util.match)
(define data (lrange 1 57))
(match (lslices data 4)
[((a b c d) ...)
(map (cut fold + 0 <>)
(list a b c d))])
(378 392 406 420)
Wrong answer: you silently cut off 57 because it wasn't followed by
three more numbers, resulting in 378 rather than 435.

1> (flow 1..58 (tuples 4 @1 0) transpose (mapcar sum))
(435 392 406 420)

Or, if we want to exclude the short tuple:

2> (flow 1..58 (tuples 4) (remove-if (lopip len (< 4))) transpose (mapcar sum))
(378 392 406 420)
--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @***@mstdn.ca
B. Pym
2024-08-14 23:38:04 UTC
Permalink
Post by B. Pym
Wow: loop macro rulez, somehow..
(loop for (a b c d) on (list 1 2 3 4 5 6 7 8) by #'cddddr
sum a into a-sum
sum b into b-sum
sum c into c-sum
sum d into d-sum
finally (return (list a-sum b-sum c-sum d-sum)))
Yeah, i might consider this code as beautiful
olivier
Gauche Scheme
(use gauche.lazy)
(use util.match)
(define data (lrange 1 57))
(match (lslices data 4)
[((a b c d) ...)
(map (cut fold + 0 <>)
(list a b c d))])
(378 392 406 420)
newLISP

(define data (sequence 1 56))

(map (curry apply +) (transpose (explode data 4)))

===>
(378 392 406 420)


Another way.

;; Using "apply" for "reduce". The 3rd argument tells
;; apply how many items to process at a time.
(apply
(fn (sums) (map + sums $args))
(cons '(0 0 0 0) data)
5)

--->
(378 392 406 420)

Loading...