Two List Tasks
January 2, 2018
For the first exercise, we create the list of lists xss, then transpose the list and map sum
over the transposed sub-lists:
> (define xss '((1 2 3 4) (2 3 4 5) (3 4 5 6))) > (map sum (apply map list xss)) (6 9 12 15)
The standard idiom for transposing a list of lists in Scheme is apply map list
.
For the second exercise, we create the input list, write an auxiliary function that splits a list of k × m items into k lists of m items, then map sum
over the sub-lists:
> (define xs '(1 2 3 4 2 3 4 5 3 4 5 6)) > (define (splits n xs) (let loop ((xs xs) (zs (list))) (if (null? xs) (reverse zs) (call-with-values (lambda () (split n xs)) (lambda (first rest) (loop rest (cons first zs))))))) > (map sum (splits 4 xs)) (10 14 18)
You can run the program at https://ideone.com/zRFVrs, where you will also see sum
and split
.
The answer to the first exercise could be simplified (in the eye of
this beholder) to:
(apply map + xss)
Another solution for the second exercise, using just R7RS Scheme.
A Haskell version.
Here’s a solution in C.
Output:
@Rutger, your solution to the first task sums elements within the sublists, as opposed to summing corresponding elements across the sublists.
Here’s a minor update that zips the lists so that the sum is across sublists.
Here’s the updated version that also supports sublists of differing lengths, padding the shorter sublists with zeros at the end.