'Addition items in list Racket

I'm working with lists in Racket, and I was doing a function to additions items. I did

(define (iter lst [acc '()])
  (if (null? lst)
      (append (list acc))
      (iter10 (cdr lst) (append acc (caar lst)))))

and i have output:

(iter10 '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))))
'((1 2 7 8))

but i want output:

(iter10 '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))))
'((1 2 7 8) (3 4 9 10) (5 6 11 12))
(iter10 '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))((1 2)(3 4)(5 6))))
'((1 2 7 8 1 2) (3 4 9 10 3 4) (5 6 11 12 5 6))

I know it's because of the use of caar, but I don't know how to do it any other way. There is a main list in which there are several list. I want all elements to be connected by position. And that the number of main list could be any. Thanks



Solution 1:[1]

Break this problem into two parts:

  • Use apply map idiom to create groups of lists with same position:
> (apply map list '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))))
'(((1 2) (7 8)) ((3 4) (9 10)) ((5 6) (11 12)))
  • Use append to append all lists in group into one list:
> (map (lambda (group) (apply append group))
       '(((1 2) (7 8)) ((3 4) (9 10)) ((5 6) (11 12))))
'((1 2 7 8) (3 4 9 10) (5 6 11 12))

Then combine these two parts into one function:

(define (iter10 lst)
  (map (lambda (group) (apply append group))
       (apply map list lst)))

Tests:

> (iter10 '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))))
'((1 2 7 8) (3 4 9 10) (5 6 11 12))

> (iter10 '(((1 2)(3 4)(5 6))((7 8)(9 10)(11 12))((1 2)(3 4)(5 6))))
'((1 2 7 8 1 2) (3 4 9 10 3 4) (5 6 11 12 5 6))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin Půda