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?
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