How to compute the length and sum of a list of integers in one pass?

132 Views Asked by At

I have the following function for computing the length and sum of a given list of integers:

fun
length_and_sum
(xs: list0(int)): $tup(int(*length*), int(*sum*)) =
$tup(length(list0), list0_foldleft(xs, 0, lam(res, x) => res + x)

This function requires two passes (that is, traverses the given list twice: once for length and once for sum). Is there a way to do this in one pass?

2

There are 2 best solutions below

0
On

Use a tuple as an accumulator, where one element stores the sum, and the other stores length.

the function which you would then pass to fold would then essentially return (res + 1, res + x) for the argument (res,x).

I am writing this answer from OCaml's perspective. The implementation might be a bit different for your case

0
On

It can be done as follows:

fun
length_and_sum
(
xs: list0(int)
) : $tup(int(*length*), int(*sum*)) =
list0_foldleft<$tup(int,int)><int>
(
  xs, $tup(0, 0), lam(res, x) => $tup(res.0 + 1, res.1 + x)
)